在不使用 split() 的情况下标记 Java 中的字符串

Tokenizing a String in Java without using split()

我正在尝试编写一种方法,将字符串标记为数组中的相应单词。我已经用 split 方法测试了我的程序,它工作正常,但我正在尝试编写一个不使用 split 的标记化方法。这是我到目前为止尝试过的:

public static String[] tokenize(String sentence) {
int wordCount = countWords(sentence);
String[] sentenceWords = new String[wordCount];
int curWord = 0;
char letter;

for(int i = 0; i < sentence.length()-1; i++) {
letter = sentence.charAt(i);
if (letter == ' ') {
  curWord++;
  continue;
}
System.out.println (sentenceWords[curWord]);
sentenceWords[curWord] = String.format("%s%c", sentenceWords[curWord], letter);
System.out.printf("%s\n", sentenceWords[curWord]);
}
return sentenceWords;
}

此方法的输出完全错误。我得到一个充满一堆空值的输出,每个单词都在一个新行上。

我也尝试了另一种变体,但没有做得太过分:

public static String[] tokenize(String sentence) {
int wordCount = countWords(sentence);
String[] sentenceWords = new String[wordCount];
for(int i = 0; i < sentence.length()-1; i++) {
if(sentence.contains(" ")) {
//Something.....
}
}
return sentenceWords;
}

我不确定正确的方法是什么。

如果您要做的是拆分每个单词并将其存储在一个数组中,这可能会有所帮助。

public static String[] tokenize(String sentence) 
{
    int wordCount = countWords(sentence);
    String[] wordArr = new String[wordCount];
    int wordCounter = 0;

    for(int i = 0; i < sentence.length(); i++)
    {
        if(sentence.charAt(i) == ' ' || i == sentence.length() - 1)
        {
            wordCounter++;

        }
        else
        {
            if(wordArr[wordCounter] == null)
            {
                wordArr[wordCounter] = "";
            }
            wordArr[wordCounter] += sentence.charAt(i);
        }

    }

    return wordArr;

}

这与您所拥有的类似,但它在添加每个字符之前初始化数组中的每个单词,这解释了为什么输出 null。

这也不只保存单词的空格,也不考虑标点符号。希望这对您有所帮助!!