Evan R.
Evan R.

Reputation: 1244

Android: way to check if a string contains any values from array?

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.

Upvotes: 1

Views: 24916

Answers (4)

Danny
Danny

Reputation: 7518

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);

Upvotes: 3

Gabriel Negut
Gabriel Negut

Reputation: 13960

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);
    }
}

Upvotes: 1

anujprashar
anujprashar

Reputation: 6335

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;
       }

    }

Upvotes: 1

Knickedi
Knickedi

Reputation: 8787

Try this:

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

Upvotes: 6

Related Questions