开发者

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

开发者 https://www.devze.com 2023-04-09 15:24 出处:网络
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 co

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 ca开发者_如何学Gon 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.


Try this:

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


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


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

    }


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

精彩评论

暂无评论...
验证码 换一张
取 消