1.I tried to use the contains function BUT it did not work, it only works when b = "30-10-1960\n" or b = "Posephine Esmerelda Bloggs\n". How to check if a contains b? 2.Here is the code I wrote.
String a = "name Posephine Esmerelda Bloggs\n" +
"birthday 30-10-1960\n" +
"address 102 Smith St, Summer hill, NSW 2130\n" +
"";
String b = "Posephine Esmerelda Bloggs\n" +
"30-10-1960\n";
System.out.println("a.contains(b)");
it works try this -
String a = "name Posephine Esmerelda Bloggs\n" +
"birthday 30-10-1960\n" +
"address 102 Smith St, Summer hill, NSW 2130\n" +
"";
String b = "Posephine Esmerelda Bloggs\n" +
"birthday 30-10-1960\n";
System.out.println(a.contains(b));
in your code there is some issue - 1. you used as a string literals in println method, it must be a reference. 2. what you are comparing is not same. In 'a' there is extra word 'birthday' that is missing in 'b'.
The correct string sequence i pasted in sample code.
I think the logic you want here is to assert that every line of the b
string appears somewhere in the a
string:
String a = "name Posephine Esmerelda Bloggs\n" +
"birthday 30-10-1960\n" +
"address 102 Smith St, Summer hill, NSW 2130\n" +
"";
String b = "Posephine Esmerelda Bloggs\n" +
"30-10-1960\n";
String[] lines = b.split("\n");
// now check each line
boolean all = true;
for (String line : lines) {
if (!a.contains(line)) {
all = false;
break;
}
}
if (all) {
System.out.println("MATCH");
}
else {
System.out.println("NO MATCH");
}
This prints:
MATCH
for the answer of the question how to find the two parts in b
String[] arr = b.split( "\n" );
int pos = a.indexOf( arr[0] + '\n' );
if( pos > -1 && a.indexOf( arr[1] + '\n', pos ) > -1 )
System.err.println( "found" );
+ '\n'
: finds the parts only if they end with a \n
if the check for the ending '\n'
is unnecessary remove both + '\n'
if the parts may be unordered the pos
argument can be omitted
without checking for the \n
at the end or the order as in the chosen solution
String[] arr = b.split( "\n" );
if( a.indexOf( arr[0] ) > -1 && a.indexOf( arr[1] ) > -1 )
System.err.println( "found" );
the solution without checking is identical to the following
if( a.contains( arr[0] ) && a.contains( arr[1] ) )
System.err.println( "found" );
…because contains(s)
returns indexOf(s.toString()) > -1
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.