我正在编写一个代码来反转字符串中的子字符串。例如: 你好,世界 结果:olleH dlrow
public class q05 {
public static void main(String[] args) {
System.out.println("Please enter a string: ");
Scanner sc=new Scanner(System.in);
String str= sc.nextLine();
int length = 0,beginString=0,j=0,i=0;
String reversedString=new String();
while(length<str.length()){ //check all the string
for(i=0;str.charAt(i)!= ' ';i++){
j++;
}
String subString= str.substring(beginString, j); // create substring
String reversedsubString=new String(); // create the blank substring
System.out.println(subString);
while(j>=0){ // reverse the substring
reversedsubString=reversedsubString+subString.charAt(j);
j--;
}
reversedString=reversedString+reversedsubString;
System.out.println(reversedString);
i++;
length++;
}
System.out.println(reversedString);
}
它给出了一个错误:java.lang.StringIndexOutOfBoundsException
错误在哪里?
答案 0 :(得分:1)
由于您没有指定效率限制,这应该有效:
public static void main(String[] args) {
String input = "Hello world";
StringBuilder sb = new StringBuilder();
String[] words = input.split(" ");
for (String word : words) {
// Second word on
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(reverse(word));
}
System.out.println(sb.toString());
}
public static String reverse(final String s) {
StringBuilder sb = new StringBuilder();
// Run from end to start
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
答案 1 :(得分:0)
这应该适合你。
public static void main(String[] args) {
System.out.println("Please enter a string: ");
Scanner sc=new Scanner(System.in);
String str= sc.nextLine();
StringBuilder reverseWords = new StringBuilder();
String[] words = str.split("\\s+"); // space(s) are the delimiters
for (String word : words) { //fetch a single word from inputted sentence
char[] charArray = word.toCharArray();
int end = word.length() - 1;//length of word
StringBuilder revWords = new StringBuilder();
for (int i = end; i >= 0; i--) {//start the loop from end to get the last char from words
revWords.append(charArray[ i]);//add the last char of word into stringbuilder
}
reverseWords.append(revWords);
reverseWords.append(" "); // separate the words
}
System.out.print(reverseWords);
}