简体   繁体   中英

One string contains another string

Need Help on String concepts in java,

 String s1="Java is oop probgramming, R1|R2|R4|R5|R";
 String s2="R";
 String s3="R2";
 String s4="R5";

I want to compare to s2, s3, s4 with s1 string compare after , I have tried fallowing

System.out.println(s3.matches(s1.substring(Options1.indexOf(","), s1.indexOf("|"))));
System.out.println(s2.matches(s1.substring(Options1.indexOf(","), s1.indexOf("|"))));

I am getting the false both statements.

I want when I compare to s2 string with s1 it should true .

I think it can be done simply with String#contains -

s1.contains(s2);
s1.contains(s3);

maybe you want something like this:

String s1="Java is oop programming, R1|R2|R4|R5|R";
String s2="R";
String s3="R2";
String s4="R5";
String[] validTargets = new String[]{s2,s3,s4};

String alternatives = s1.split(",")[1].trim();
for(String s: alternatives.split("|")){
    for(String t: validTargets){
        if(s.matches(t)) { //you can also use equals() here..
            System.out.println("they are matched!");
        }
    }
}

it will compare the substrings separated by | after , - with your targets (s2,s3,s4 in this case) and check whether they are exactly the same string or not..

You may use regular expressionas shown below :

System.out.println(s1.matches("(?i).*"+s2+"*"));
System.out.println(s1.matches("(?i).*"+s3+"*"));
System.out.println(s1.matches("(?i).*"+s4+"*"));  

If you want to compare it after , than get substring of string s1 and than use above code.

 s1 = s1.substring(s1.indexOf(","));

May this help you.

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