This site requires JavaScript, please enable it in your browser!
Greenfoot back
h123n
h123n wrote ...

2015/5/29

Splitting up strings?

h123n h123n

2015/5/29

#
Hi, I have looked over the internet to try and find some examples of splitting a string (which contains a sentence) And all the examples involve making a new class. Is there a method that splits it up? could you provide an example? I won't provide any code because it is not necessary. All help is appreciated, thanks for your time.
Super_Hippo Super_Hippo

2015/5/29

#
danpost danpost

2015/5/29

#
You may want to check out the 'split' methods on the same page -- #split(String) and #split(String,int)
h123n h123n

2015/5/29

#
okay, I have had a look at the methods but could you provide an example of the sentence at the beginning, what the code looks like and the output, I don't get what all the extra strings/ints like regex are for
danpost danpost

2015/5/29

#
Do not worry about 'regex' for now (that is just a limiting value for the number of "words" to be extracted from the sentence). Use the more simple 'split(String)' method. The String parameter is the separator String -- a simple space ( " " ) should do for it. If you have excess whitespace in your sentence, you may end up with empty Strings in the returned array of Strings which may need to be removed (depends on what you are doing with the words of the parsed String).
h123n h123n

2015/5/29

#
It can not find the method split(String). Please tell me what I'm doing wrong.
1
2
3
4
public void sentence2()
{
    split (Answer, 900);
}
h123n h123n

2015/5/29

#
The line is splitting up the answer with a max capacity of 900. (I just put that in because it requires regex)
danpost danpost

2015/5/29

#
h123n wrote...
It can not find the method split(String). Please tell me what I'm doing wrong.
1
2
3
4
public void sentence2()
{
    split (Answer, 900);
}
There are several issues with the way you are using the 'split' method (in line 3): (1) it is written as if you were calling a 'split' method within the same class or a class that class extends; (it needs to be executed on a String object) (2) 'Answer' is used as if it were a specific String object (I get the feeling that it is actually the name of a Class within your project, which cannot be used here); (a Class is not a String object) (3) the 'split' method of the String class returns an array of String objects which must be placed in a array to access its elements; (4) again, the 'regex' value is not needed. The following is an example of its use:
1
2
3
String sentence = "How about a nice Hawaiian Punch?";
String[] words = sentence.split(" ");
for (int n=0; n<words.length; n++) System.out.println(words[n]);
would give the following output:
1
2
3
4
5
6
How
about
a
nice
Hawaiian
Punch?
You need to login to post a reply.