Reputation: 1
I'm trying to separate the words in a sentence. Each word of the sentence is stored into the string word
, and then it adds everything back into one string again.
But why do I get an error with the substring line?
String sent = IO.readString();
char x;
String word ="";
int count = 0;
for(int i = 0; i < sent.length(); i++){
x = sent.charAt(i);
if(x == ' ')
{
word = sent.substring(x-count,x);
word = word + ' ';
count =0;
}
count++;
}
Upvotes: 0
Views: 64
Reputation: 43342
You should consider using String.split()
, which returns a String
array.
Documentation: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
To use spaces and punctuation as a separator, you could do something like this:
String[] arrWords = sentence.split("([ ,.]+)");
If you really want to go with your original route, you'll have to add some special cases for the first word and last word. Although, what happens when there are multiple spaces, or punctuation? Test it and find out!
public class SeparateWords
{
public static void main(String[] args)
{
String sent ="Hello there how are you";
char x;
String word ="";
int count = 0;
for(int i = 0; i <= sent.length(); i++){
if (i == sent.length()){
word = sent.substring(i-count+1,i);
System.out.println(word);
break;
}
x = sent.charAt(i);
if(x == ' ')
{
if ((i-count) == 0){
word = sent.substring(i-count,i);
}
else{
word = sent.substring(i-count+1,i);
}
System.out.println(word);
word = word + ' ';
count =0;
}
count++;
}
}
}
Output:
Hello
there
how
are
you
Upvotes: 1
Reputation: 201537
Because x
is a char
, not an int
, here
word = sent.substring(x-count,x);
and it should (probably) be something like
word = sent.substring(i-count,i);
because i
is the position in the String
.
Upvotes: 1
Reputation: 1138
word = sent.substring(x-count,x);
should be word = sent.substring(i-count,i);
Upvotes: 3