Reputation: 424
I was wondering in Java how I could print a string until it reaches the word "quit" in that string and then instantly stop printing at that point. For instance if the string value was:
"Hi there this is a random string quit this should not be printed"
All that should be printed is "Hi there this is a random string".
I was trying something like this, but I believe it to be wrong.
if ( input.indexOf( "quit" ) > -1 )
{
//code to stop printing here
}
Upvotes: 1
Views: 4781
Reputation: 424993
This has a one-line solution:
System.out.println(input.replaceAll("quit.*", ""));
String.replaceAll()
takes a regex to match, which I've specified to be "the literal 'quit' and everything following", which is to be replaced by a blank ""
(ie effectively deleted) from the returned String
Upvotes: 2
Reputation: 2323
Looks like homework, so this answer is in homework style. :-)
You're on the right track.
Save the value of that indexOf to an integer.
Then it's like you have a finger pointing at the right spot - ie, at the end of the substring you really want to print.
That's a hint anyway...
EDIT: Looks like people are giving it to you anyway. But here are some more thoughts:
replaceAll
solution above to cover for leading whitespace into `quit'.Upvotes: 3
Reputation: 992955
Instead of thinking about the problem as "how to stop printing" (because once you start printing something in Java it's pretty hard to stop it), think about it in terms of "How can I print only the words up to a certain point?" For example:
int quit_position = input.indexOf("quit");
if (quit_position >= 0) {
System.out.println(input.substring(0, quit_position));
} else {
System.out.println(input);
}
Upvotes: 4
Reputation: 23268
If you don't mind trailing spaces in your string
int index = input.indexOf("quit");
if (index == -1) index = input.length();
return input.substring(0, index);
Upvotes: 1