user569322
user569322

Reputation:

Checking the end of a string in Java multiple times?

So in Java, I know that str.endsWith(suffix) tests if str ends with something. Let's say I have a text with the line "You are old" in it. How would I take the "old" and set it as a variable so I can print it out in the console?

I know I could do:

if(str.endsWith("old")){ 
   String age = "old";
}

But then I'm going to have more options, so then I'd have to do:

if(str.endsWith("option1")){ 
   String age = "option1";
}

if(str.endsWith("option2")){ 
   String age = "option2";
}

...

Is there a more efficient and less verbose way to check the end of strings over writing many, possibly hundreds, of if statements

Format:
    setting: option
    setting2: option2
    setting3: option3 ...

Regardless of what "option" is, I want to set it to a variable.

Upvotes: 0

Views: 5762

Answers (6)

tskuzzy
tskuzzy

Reputation: 36446

You could use this Java code to solve your problem:

String suffix = "old";

if(str.endsWith(suffix)) {
    System.out.println(suffix);
}

Upvotes: 0

yoozer8
yoozer8

Reputation: 7489

If you are working with sentences and you want to get the word, do

String word = str.substring(str.lastIndexOf(" "));

You may need a +1 after the lastIndexOf() to leave the space out. Is that what you are looking for?

Upvotes: 2

Peaches491
Peaches491

Reputation: 1239

If you're worried about repeating very similar code, the answer is always (99%) to create a function,

So in your case, you could do the following:

public void myNewFunction(String this, String that){
    if(this.endsWith(that)){ 
    String this = that;

    }
}

...

String str = "age: old";
myNewFunction(str, "old"); //Will change str
myNewFunction(str, "new"); //Will NOT change str

And if that is too much, you can create a class which will do all of this for you. Inside the class, you can keep track of a list of keywords. Then, create a method which will compare a given word with each keyword. That way, you can call the same function on a number of strings, with no additional parameters.

Upvotes: 0

Kurru
Kurru

Reputation: 14321

Is this what you're looking for?

List<String> suffixes = new ArrayList<String>();
suffixes.add("old");
suffixes.add("young");

for(String s: suffixes)
{
    if (str.endsWith(s))
    {
        String age = s;

        // .... more of your code here...
    }
}

Upvotes: 0

talnicolas
talnicolas

Reputation: 14053

Open your file and read the line with the readLine() method. Then to get the last word of the string you can do as it is suggested here

Upvotes: 1

Mike Thomsen
Mike Thomsen

Reputation: 37506

You mean like:

String phrase = "old";
if(str.endsWith(old)){ 

Upvotes: 0

Related Questions