3

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 want each character individually like this: M y n a m e s etc.

2
  • 7
    can you be more specific - what do you mean by "gaps"? Commented Apr 2, 2011 at 16:06
  • 4
    Some examples of both input and output would be useful. As the question currently stands, I'm not sure anyone can answer it. Commented Apr 2, 2011 at 16:07

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

6 Comments

sorry my question was not complete....i wanted to mean if in a sentence like:My Names James....here I want each characters individually like:M y n a m e s ...this way...
There it is char[] characters = sentence.toCharArray(); Then you can use a loop to filter or whatever...
Just iterate over the chars in the string?
Also he could do that, but i think he wants to store them first in a char[]
replace(char oldChar, char newChar). You have it in the api i gave you.
|
0
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"));

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.