首页 > 解决方案 > 不使用 split() 拆分单词

问题描述

我设法用某个符号分割给定的单词或句子,现在我想知道是否可以将多个符号作为字符串来做到这一点。例如,如果我有 ("1+1=2"),并尝试将其拆分为 ("+=")?

我考虑过将 symbol 声明为字符串,然后将我已经拥有的循环放在另一个循环中,以便为 symbol 中的每个字符测试 word 中的任何字符,但老实说,这让我感到困惑。

^-^ 我很感谢任何建议。

公共静态无效 splitBySymbol() {

    int i = 0;

    while (i < word.length()) {

      if (word.charAt(i) == symbol) {

          System.out.println( word.substring(0,i)); ;

          word = word.substring(i + 1);

          i = -1;

      }

      i++;
    }


}

标签: javasplit

解决方案


如果您只想打印零件,您可以:

public static void splitBySymbol(String word, String symbols)
{
    // Check each char
    for (int i = 0; i < word.length(); i++) {
        // Get the current char and convert to string (for contains())
        String c = Character.toString(word.charAt(i));
        // If it is a delimeter, print a new line
        if (symbols.contains(c)) {
            System.out.println();
        }
        // Otherwise, print the char
        else {
            System.out.print(c);
        }
    }
}

推荐阅读