java java字符串分割

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5524243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:32:06  来源:igfitidea点击:

java string split

java

提问by Nawshad Farruque

What should I do if I want to split the characters of any string considering gaps and no gaps?

如果我想拆分任何字符串的字符时要考虑间隙和无间隙,该怎么办?

For example, if I have the string My Names JamesI want each character individually like this: M y n a m e setc.

例如,如果我有一个字符串,My Names James我希望每个字符都像这样:M y n a m e s等。

回答by sfrj

You mean this?

你是这个意思?

   String sentence = "Hello World";
   String[] words = sentence.split(" ");

Also if you would like to get the chars of the string you could do this:

另外,如果您想获取字符串的字符,您可以这样做:

char[] characters = sentence.toCharArray();

Now you just need a loop to iterate the characters and do whatever you want with them.

现在您只需要一个循环来迭代字符并使用它们做任何您想做的事情。

Here a link to the java API documentation there you can find information about the String class.

这里有一个指向 java API 文档的链接,您可以在那里找到有关 String 类的信息。

http://download.oracle.com/javase/6/docs/api/

http://download.oracle.com/javase/6/docs/api/

I hope this was useful to you.

我希望这对你有用。

回答by corsiKa

class MindFreak {
    static String makeSpaced(String s) {
        StringBuilder res = new StringBuilder();
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(!Character.isWhitespace(c)) {
                res.append(c).append(" ");
            }
        }
        return res.toString();
    }

    public static void main(String[] args) {
        System.out.println(makeSpaced("My Names James"));
        System.out.println(makeSpaced("Very    Spaced"));

    }
}