Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 切碎字符串_Java_String_Indexoutofboundsexception - Fatal编程技术网

Java 切碎字符串

Java 切碎字符串,java,string,indexoutofboundsexception,Java,String,Indexoutofboundsexception,我试图将一个长字符串分割成每个单词,并在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++)

我试图将一个长字符串分割成每个单词,并在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);
    }
}
公共类拼写检查器{
公共静态无效测试(字符串str){
int i=0,j=0,n=str.length();
字符串temp=“”;
做{
对于(i=j;str.charAt(i)!='';i++)
温度+=str.charAt(i);
温度+='\0';
系统输出打印项次(温度);
温度=”;
j=i+1;

}而(j这将满足您的需求:

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

如果我理解了你的问题,你可以重写
test(String)
来使用

public static void test(String str) {
    String[] words = str.split("\\s+");
    for (String word : words) {
        System.out.println(word);
    }
}
您正在使用
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
    }
}

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

您能解释一下您在测试函数中的操作吗?此代码与DesireEdit的不同之处在于,最好不要在循环中
+=
字符串:它变为
O(n²)
操作。谢谢,我会记住这一点。这是0.1版,所以我甚至没有考虑过复杂的场景。以后一定会小心的。@StriplingWarrior谢谢,我把它改成了使用
StringBuilder
谢谢你指出了那一个。你的代码绝对没问题,但我还是设法保持了我的“穴居人”在获取整个字符串之前添加空格,即在循环中编辑字符串之前添加“
str+=”;
”。
for(i=j;str.charAt(i)!=' ';i++)
temp+=str.charAt(i);