原文:
Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)
译文:
写代码翻转一个C风格的字符串。(C风格的意思是"abcd"需要用5个字符来表示,包含末尾的 结束字符)
写了多个字符串翻转的方法:
package Arrays_Strings;
import java.util.Stack;
public class S1_2 {
// 首尾位置交换
public static String reverse1(String s) {
char[] cc = s.toCharArray();
int len = s.length();
for(int i=0; i
Java库函数
public static String reverse2(String s) {
return new StringBuilder(s).reverse().toString();
}
// 反向添加
public static String reverse3(String s) {
String ret = "";
for(int i=s.length()-1; i>=0; i--) {
ret += s.charAt(i);
}
return ret;
}
// 递归1
public static String reverse4(String s) {
StringBuilder ret = new StringBuilder();
rec(new StringBuilder(s), ret, 0);
return ret.toString();
}
// 不能用String作为param,否则无法改变String的值,建议一律采用StringBuilder
public static void rec(StringBuilder src, StringBuilder dest, int pos) {
if(pos == src.length()) {
return;
}
rec(src, dest, pos+1);
dest.append(src.charAt(pos));
}
// 递归2
public static String reverse5(String s) {
if(s.length() <= 1) {
return s;
}
return reverse5(s.substring(1)) + s.charAt(0);
}
// =========================================
// 输入“I am a student.”,则输出“student. a am I”
public static String reverseSentence1(String s) {
// 翻转“I am a student.”中所有字符得到“.tneduts a ma I”,
// 再翻转每个单词中字符的顺序得到“students. a am I”
String reversedSentence = reverse1(s);
String[] ss = reversedSentence.split(" ");
String ret = "";
for(int i=0; i
stack = new Stack
(); String ret = ""; // 先将整句话倒着进栈 for(int i=s.length()-1; i>=0; i--) { char c = s.charAt(i); if(c == ' '){ // 进栈前检查是否为" ",如果为TRUE,先将依次POP() while( !stack.isEmpty() ) { ret += stack.pop(); } ret += " "; } else{ stack.push(c); } } // 栈内可能还有剩下的字符 while( !stack.isEmpty() ) { ret += stack.pop(); } return ret; } public static void main(String[] args) { String s = "abc"; System.out.println(reverse1(s)); System.out.println(reverse2(s)); System.out.println(reverse3(s)); System.out.println(reverse4(s)); System.out.println(reverse5(s)); s = "I am a student."; System.out.println(reverseSentence1(s)); System.out.println(reverseSentence2(s)); } }