开发者

java string split

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 James I wan开发者_运维知识库t each character individually like this: M y n a m e s etc.


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.

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

I hope this was useful to you.


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"));

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜