1

I've tried searching for "Java check if string contains values from array", and other variations on that, but have not come up with anything so hoping someone can help me. I've got the following code that I would like to clean up:

if (dateint.contains("th")){
        dateint=dateint.substring(0, dateint.length()-2);
    } else if (dateint.contains("st")){
        dateint=dateint.substring(0, dateint.length()-2);
    } else if (dateint.contains("nd")){
        dateint=dateint.substring(0, dateint.length()-2);
    } else if (dateint.contains("rd")){
        dateint=dateint.substring(0, dateint.length()-2);
    }

I'm wondering if I can do something like the following (not true code, but thinking in code):

String[] ordinals = {"th", "st", "nd", "rd"};
if dateint.contains(ordinals) {
dateint=dateint.substring(0, dateint.length()-2);
}

basically checking if any of the values in the array are in my string. I'm trying to use the least amount of code reuqired so that it looks cleaner than that ugly if/else block, and without using a for/next loop..which may be my only option.

4 Answers 4

6

Try this:

for (String ord : ordinals) {
    if (dateint.contains(ord)) {
        dateint = dateint.substring(0, dateint.length() - 2);
        break;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this worked perfectly! thanks to everyone else who replied as well, was hoping for a 1/2 line solution using built in code but this will do.
3

If you are up to using other libraries, the Apache StringUtils can help you.

StringUtils.indexOfAny(String, String[])

if(StringUtils.indexOfAny(dateint, ordinals) >= 0)
    dateint=dateint.substring(0, dateint.length()-2);

Comments

1

you can use for loop for that

    for(int i = 0;i < ordinals.length;i++){
      if dateint.contains(ordinals[i]) {
        dateint=dateint.substring(0, dateint.length()-2);
        break;
       }

    }

Comments

1

Use an extended for loop :

String[] ordinals = {"th", "st", "nd", "rd"};

for (String ordinal: ordinals) {
    if dateint.contains(ordinal) {
        dateint=dateint.substring(0, dateint.length()-2);
    }
}

1 Comment

It saved me I used this logic to build my own...an it works :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.