【问题标题】:Butchering a String word wise明智地屠宰一个字符串
【发布时间】:2014-10-08 19:35:28
【问题描述】:

我试图将一个长字符串分成每个单词并在 Java 中按顺序打印它们,但它会引发异常 StringIndexOutOfBounds。这是代码,任何输入都非常感谢:

public class SpellingChecker {
public static void test(String str) {
    int i=0,j=0,n=str.length();
    String temp="";
    do{
        for(i=j;str.charAt(i)!=' ';i++)
            temp+=str.charAt(i);
        temp+='\0';
        System.out.println(temp);
        temp="";
        j=i+1;
    }while(j<n);
}
public static void main(String[] args) {
    java.util.Scanner input = new java.util.Scanner(System.in);
    System.out.print("Enter string for which you want to check spelling : ");
    String strng=input.next();
    test(strng);
    }
}

【问题讨论】:

  • 你能解释一下你在测试功能中的表现吗?
  • 这段代码的作用与预期不同

标签: java string indexoutofboundsexception


【解决方案1】:

您正在使用next() 而不是nextLine() 来扫描您的句子。所以你只会得到第一个单词而不是所有单词..

所以改成

String strng = input.nextLine();

接下来在您的 test() 方法中,这应该是模板

public static void test(String str) {
    String[] words = str.split("\\s+");
    for(String word: words) {
        System.out.println(word);
        //Here decide what you want to do with each word
    }
}

【讨论】:

  • 感谢您指出这一点。您的代码绝对没问题,但我设法通过在输入整个字符串之前添加一个空格来保持我的“穴居人”版本,即str+=' ';,然后在循环中对其进行编辑。
【解决方案2】:

如果我理解你的问题,你可以重写 test(String) 以使用 String.split(String) 类似的东西,

public static void test(String str) {
    String[] words = str.split("\\s+");
    for (String word : words) {
        System.out.println(word);
    }
}

【讨论】:

    【解决方案3】:

    这会做你想做的事:

    String[] words = str.split("\\s+");
    StringBuilder temp = new StringBuilder();
    for (String word : words)
        temp.append(word).append("\0");
    

    【讨论】:

    • 最好不要在循环中使用+= 字符串:它会变成O(n²) 操作。
    • 谢谢,我会记住的。这是 0.1 版,所以我什至没有考虑复杂性场景。以后一定会好好照顾的。
    • @StriplingWarrior 谢谢,我把它改成了StringBuilder
    【解决方案4】:
    for(i=j;str.charAt(i)!=' ';i++)
    temp+=str.charAt(i);
    

    如果字符串中没有任何空格,我认为这超出了范围

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 2011-01-01
      • 2012-02-16
      • 2012-01-19
      • 1970-01-01
      相关资源
      最近更新 更多