l'm trying to create two functions. One: that shows 'true' if the c variable appears at least ONCE in the String variable. Two: The same function but shows the position of the letter. More specifically,the seqSearchPos function (String s, char c) searches if c appears in s. function returns the position of c to s if it exists. If c does not exist the function will return -1.
l sadly do not know how to appoarch this problem, this specific problem regarding String and char.There must be a method that l still do not know that can help me in this matter
public static boolean seqSearch(String s, char c) {
boolean found=false;
if(s.equals(c)) {
found=true;
}
return found;
}
Main:
String s="e";
char c='e';
System.out.println(seqSearch(s,c));
public static int seqSearchPos(String s,char c) {
int position=-1;
for(int i=0; i<s.length(); i++) {
if(s.equals(c)) {
position=i;
break;
}
}
return position;
}
Main:
String s="hello";
char c='e';
System.out.println(seqSearchPos(s,c));
I expected to show true in the first one and in the second the position 1 but it showed false and -1 respectively.
There is a bug in this line of code:
if(s.equals(c)) {
It is comparing the entire string with the character, and it (obviously) does not match.
You need to compare the single character at the index in the string:
if (s.charAt(i) == c) {
As an aside, you might also use return
directly from the if
statement. This will let you remove the position
variable and make the code a bit shorter:
public static int seqSearchPos(String s, char c) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
return i;
}
}
return -1;
}
There is also an String.indexOf(int c) method that does exactly what you need and would let you write the method like this:
public static int seqSearchPos(String s, char c) {
return s.indexOf(c);
}
Or, even better, simply call that String method directly instead of wrapping it in your own function.