简体   繁体   中英

Android - How to check the existence of a string value in another comma separated string

Android - How to check the existence of a string value in another comma separated string .

 String all_vals  = "617,618,456,1,234,5,5678,225";
 String check_val= "456";

How to check like,

 if (all_vals contains check_val) { 

 }

Convert the comma-separated string to an array with split , then convert it to a List with Arrays.asList , then use contains .

String all_vals = "617,618,456,1,234,5,5678,225";
List<String> list = Arrays.asList(all_vals.split(","));
if (list.contains(check_val)) {

}

This will prevent the false positives from just checking if the substring exists in the list with contains directly on the string all_vals , eg all_vals.contains("4") would return true in the direct String#contains case.

    String all_vals  = "617,618,456,1,234,5,5678,225";
    String check_val= "5678";
    int place = 1;

    String[] strings = all_vals.split(",");
    for (String str : strings) {
        if(str.equals(check_val))
        {
            System.out.println("We have string in all_val on place: " + place);
        }
        place++;
    }
String all_vals  = "617,618,456,1,234,5,5678,225";  
String check_val= "456";

if (all_vals.startsWith(check_val) || 
    all_vals.endsWith(check_val) || 
    all_vals.contains("," + check_val + ","))
{
    System.out.println("value found in string");
}

Java 8:

String all_vals  = "617,618,456,1,234,5,5678,225";
String check_val= "5678";
Arrays.stream(all_vals.split(",")).anyMatch(check_val:: equals)
if(Arrays.stream(all_vals.split(",")).anyMatch(check_val:: equals)){
    System.out.println("The value is present");
 }

Ref :: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence)

public boolean contains(CharSequence s)

Returns true if and only if this string contains the specified sequence of char values.

Ex

/******************************************************************************
                 public boolean contains(CharSequence s)
*******************************************************************************/


public class Main
{
    public static void main(String[] args) {
        String all_vals  = "617,618,456,1,234,5,5678,225";
        String check_val= "456";
        System.out.println("String contains :: "+all_vals.contains(check_val));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM