Twisterz
Twisterz

Reputation: 424

Print string up to a certain word - Java

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

Answers (4)

Bohemian
Bohemian

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

azhrei
azhrei

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:

  1. You might want to think about upper and lower case as well.
  2. Also consider what you are going to do if 'quit' is not there.
  3. Also the solutions here don't strictly solve your problem - they'll print unnecessary spaces too, after the last word ends, before 'quit' starts. If that is a problem you consider String Tokenization or an adapation of the replaceAll solution above to cover for leading whitespace into `quit'.

Upvotes: 3

Greg Hewgill
Greg Hewgill

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

Jesus Ramos
Jesus Ramos

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

Related Questions