String matching: Difference between revisions

(GDScript)
Line 2,504:
 
=={{header|Java}}==
For this task consider the following strings
<syntaxhighlight lang="java">
String string = "string matching";
String suffix = "ing";
</syntaxhighlight>
The most idiomatic way of determining if a string starts with another string is to use the ''String.startsWith'' method.
<syntaxhighlight lang="java">
string.startsWith(suffix)
</syntaxhighlight>
Another way is to use a combination of ''String.substring'' and ''String.equals''
<syntaxhighlight lang="java">
string.substring(0, suffix.length()).equals(suffix)
</syntaxhighlight>
To determine if a string contains at least one occurrence of another string, use the ''String.contains'' method.
<syntaxhighlight lang="java">
string.contains(suffix)
</syntaxhighlight>
A slightly more idiomatic approach would be to use the ''String.indexOf'' method, which will also return the index of the first character.
<syntaxhighlight lang="java">
string.indexOf(suffix) != -1
</syntaxhighlight>
The most idiomatic way of determining whether a string ends with another string is to use the ''String.endsWith'' method.
<syntaxhighlight lang="java">
string.endsWith(suffix);
</syntaxhighlight>
Similarly, a combination of ''String.substring'' and ''String.equals'' can be used.
<syntaxhighlight lang="java">
string.substring(string.length() - suffix.length()).equals(suffix)
</syntaxhighlight>
If you're looking to find the index of each occurrence, you can use the following.
<syntaxhighlight lang="java">
int indexOf;
int offset = 0;
while ((indexOf = string.indexOf(suffix, offset)) != -1) {
System.out.printf("'%s' @ %d to %d%n", suffix, indexOf, indexOf + suffix.length() - 1);
offset = indexOf + 1;
}
</syntaxhighlight>
<pre>
'ing' @ 3 to 5
'ing' @ 12 to 14
</pre>
<br />
Alternately
<syntaxhighlight lang="java">"abcd".startsWith("ab") //returns true
"abcd".endsWith("zn") //returns false
Line 2,510 ⟶ 2,554:
int loc = "abab".indexOf("bb") //returns -1
loc = "abab".indexOf("ab") //returns 0
loc = "abab".indexOf("ab",loc+1) //returns 2</syntaxhighlight>
</syntaxhighlight>
 
<syntaxhighlight lang="java">
// -----------------------------------------------------------//
public class JavaApplication6 {
 
public static void main(String[] args) {
String strOne = "complexity";
String strTwo = "udacity";
 
//
stringMatch(strOne, strTwo);
 
}
 
Line 2,549 ⟶ 2,589:
}
}
</syntaxhighlight>
 
=={{header|JavaScript}}==
118

edits