Reputation:
it should return true as there is 'c' in the string S but it keeps returning False?
public class A {
public static void main(String[] args){
System.out.println(contains('c', "cccc"));
}
public static boolean contains(char c, String s) {
boolean to_return = true;
while(true) {
if(s.equals("")){
return to_return = false;
} else {
char c2 = s.charAt(0);
if(c==c2) {
to_return = true;
}
}
s=s.substring(1);
}
}
}
I have NO idea why it isnt? it only returns false if the string is empty which is clearly is(I am NOT allowed to use for loops etc..
Upvotes: 0
Views: 57
Reputation: 12870
works:
public static boolean contains(char c, String s) {
return s.indexOf(c) != -1;
}
Upvotes: 1
Reputation: 98
Can you try a more cleaner method, it seems too cluttered.
public static boolean contains(char c, String s) {
if (s == null)
return false;
if (s.equals(""))
return false;
int size = s.length();
for (int i = 0; i < size; i ++) {
if(s.charAt(i) == c)
return true;
}
return false;
}
Upvotes: 0
Reputation: 8825
If you want a loopy version, use a for loop like this, as it should be cleaner:
public static boolean contains(char c, String s) {
boolean to_return = true;
for(int i=0;i<s.length();i++) {
if(s.charAt(i) != c) {
to_return = false;
}
}
return to_return;
}
Alternatively, you can just do:
public static boolean contains2(char c, String s) {
return s.contains(String.valueOf(c));
}
Upvotes: 0
Reputation: 68935
you are not returning true
anywhere in your code. So recursion happens till s.equals("")
is evaluated to true
and returns false
.
Change
if(c==c2) {
to_return = true;
}
to
if(c==c2) {
return true;
}
Upvotes: 2