Erengazi Mutlu :
I was trying to implement a method that finds the first index of any characters from a set in a given string.For example, firstInSet("spring", "aeiou") returns 3 because 'i' occurs in the set "aeiou" and the preceding characters do not. Also if there is no match or null it should return -1. Here is my code. What is the problem?(Btw this is the first time I'm asking a question, if I violate any rules, I'm sorry)
public class Strings
{
/**
Finds the first occurrence of any of the characters in a set.
@param str the string to search
@param set the set of characters to match
@return the index of the first character in str that occurs in set,
or -1 if there is no match or one of the arguments is null
*/
public int firstInSet(String str, String set)
{
for (int i = 0; i < set.length(); i++ )
{
for (int j = 0; j < str.length(); j++)
{
if( set.substring(i,i+1) == str.substring(j,j+1) )
{
return set.indexOf(i);
}
}
}
return -1;
}
}
WJS :
As I understand it you want to find the first index of a character in str
that is in set
. So if you had the String str = "unknown"
. The answer would be 0 for the first u.
public static int firstInSet(String str, String set) {
int pos = 0;
for (char c : str.toCharArray()) {
int i = set.indexOf(c);
if (i >= 0) {
return pos;
}
pos++;
}
return -1;
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=356802&siteId=1