【问题标题】:Tokenizing a String in Java without using split()不使用 split() 在 Java 中标记字符串
【发布时间】:2023-03-11 05:51:01
【问题描述】:

我正在尝试编写一种方法来将字符串标记为其各自的单词到一个数组中。我已经用 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;
}

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

【问题讨论】:

  • 您好,您介意格式化源代码吗?让帮助更容易
  • 可以考虑使用正则表达式。
  • 为什么,你有工作代码。为什么要改变它?还有很多其他方法可以做到这一点,例如将其传递给Scanner 或正则表达式。手写你自己的循环很容易是其中最糟糕的。

标签: java arrays string tokenize


【解决方案1】:

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

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。

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

【讨论】:

  • i == sentence.length() 在这段代码中永远不会是真的,如果可以的话,它应该首先被测试。
  • @EJP 你说得对,我只是看了一下,我猜,谢谢。
  • BreakIterator 不够吗?
猜你喜欢
  • 2014-05-03
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多