Comparing two strings

H

HS1

Hello all

I want to compare two string to see whether they have a matching pattern or
not. For example:
"we are students" will match with "are"
I tried functions string.matches or string.regionMatches but they did not
work

Could you please help
Thank you
SH1
 
R

Rob van der Leek

Hello all

I want to compare two string to see whether they have a matching pattern or
not. For example:
"we are students" will match with "are"
I tried functions string.matches or string.regionMatches but they did not
work

What you are looking for is a substring match, you can accomplish this
with the indexOf(...) method, e.g.:

public class T {
public static void main(String args[])
{
String s1 = "we are students";
String s2 = "are";
int startIndex = s1.indexOf(s2);
if (startIndex > 0) {
System.out.println("Found substring at: " + startIndex);
}
else {
System.out.println("Found no match");
}
}
}

Regards,
 
M

MaSTeR

public class T {
public static void main(String args[])
{
String s1 = "we are students";
String s2 = "are";
int startIndex = s1.indexOf(s2);
if (startIndex > 0) {
System.out.println("Found substring at: " + startIndex);
}
else {
System.out.println("Found no match");
}
}
}

Actually
if (startIndex != -1) {
System.out.println("Found substring at: " + startIndex);
}
else {
System.out.println("Found no match");
}
}
}

Otherwise wouldn't find a match for
String s1 = "we are students";
String s2 = "we";
 
R

Rob van der Leek

public class T {
public static void main(String args[])
{
String s1 = "we are students";
String s2 = "are";
int startIndex = s1.indexOf(s2);
if (startIndex > 0) {
System.out.println("Found substring at: " + startIndex);
}
else {
System.out.println("Found no match");
}
}
}

Actually
if (startIndex != -1) {
System.out.println("Found substring at: " + startIndex);
}
else {
System.out.println("Found no match");
}
}
}

Otherwise wouldn't find a match for
String s1 = "we are students";
String s2 = "we";

Oops, you're right, actually I always use >= .

Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top