2015-10-25 35 views
1

因此,我试图对一个句子进行反转,即使编译时没有任何错误,它也会告诉我我的反向句是超出界限的。java中的句子相反

- 它应该像这样工作:“你好,世界!” ! - > dlrow,2009东海生日贺”

所述代码:

String sentence="this is a sentence!"; 
    String reverseSentence=sentence; 
    for(int counter=0;counter<sentence.length();counter++) 
    { 
     char charToReplace,replaceChar; 

     charToReplace = reverseSentence.charAt(counter); 
     replaceChar = sentence.charAt(sentence.length()-counter); 

     reverseSentence=reverseSentence.replace(charToReplace, replaceChar); 

     System.out.println(reverseSentence); 
    } 
+2

'replace'不会做你认为它在这里。阅读它的Javadoc。 – Tunaki

+0

为什么要替换?为什么不使用StringBuilder并以相反的顺序追加输入字符串的字符? – GhostCat

回答

2

原因你所得到的例外是,在sentence.charAt(sentence.length()-counter)sentence.length()-counter是出界时,计数器为0应该是sentence.length()-1-counter

。然而,正如Tunaki所说,你的代码还有其他问题,我建议你使用 StringBuilder来构造反转的 String,而不是使用 replace(它将用第二个字符替换任何第一个字符的出现)。
+0

谢谢伊兰!尝试过,做它应该做的! –

1

它不会显示错误,因为有关索引的异常发生在RunTime。

这里:

replaceChar = sentence.charAt(sentence.length()-counter); 

你试图访问你的字符串(19-0)的指数19。其替换为:

replaceChar = sentence.charAt(sentence.length()-counter-1); 

我会建议使用在你的情况StringBuilder虽然。

要么使用reverse()方法:

String sentence = "this is a sentence!"; 
String reversed = new StringBuilder(sentence).reverse().toString(); 
System.out.println(reversed); // Prints : !ecnetnes a si siht 

或者使用append()方法构建新的String对象。这使用较少的内存比使用String,因为它不是你循环每次创建一个新的String对象:

String sentence = "this is a sentence!"; 
StringBuilder reversed = new StringBuilder(); 

for (int i = 0 ; i < sentence.length() ; i++){ 
    reversed.append(sentence.charAt(sentence.length() - 1 - i)); 
} 

System.out.println(reversed.toString()); // Prints : !ecnetnes a si siht 
1

您可以使用字符数组来实现这样您的要求,

String sentence = "ABDEF"; 
    char[] firstString = sentence.toCharArray(); 
    char[] reversedString = new char[sentence.length()]; 

    for (int counter = 0; counter < sentence.length(); counter++) { 
     reversedString[counter] = firstString[sentence.length() - counter -1]; 
    } 
    System.out.println(String.copyValueOf(reversedString)); 
0

最好不要做任何替换或循环。它从字符串中创建一个char数组,反转数组,然后从反向数组创建一个字符串,这将完成你没有任何移动部件或替换的要求。例如:

String hw = "hello world"; 
    char[] hwChars = hw.toCharArray(); 
    ArrayUtils.reverse(hwChars); 
    String wh = new String(hwChars); 
    System.out.println(wh); 
0

就在每个空格分割字符串,并把它放在String数组,然后以相反的顺序打印阵列

public static void main(String[] args) { 
    String sentence = "this is a sentence!"; 
    String[] reverseSentence = sentence.split(" "); 

     for (int i = reverseSentence.length-1; i >= 0; i--) { 
     System.out.print(" " + reverseSentence[i]); 
     } 

    } 
+0

这会以相反的顺序在句子中打印单词,但单词中的字符仍按正确的顺序排列。操作指南中也包含了相反字符中的字符。 – robjwilkins