counting letters in a string?
public int countLetter(char let){
int index = 0;
int count = 0;
while (index<string.length())
if (string.charAt(index)==let){
count++;
}
index++;
return count;
}
the goal of this part of the program is to have the user input a string (string) and a char (let) and then count the number of times that character appears in the string. i'm trying to make it case insensitive. i thought about using equalsIgnoreCase or toUpperCase but i can't change 'let' to a string. any ideas? thx>
ok i tried implementing some of what you guys said, do you think this will work?
public int countLetter(char let){
int index = 0;
char c = Character.toUpperCase(let);
int count = 0;
while (index<string.length())
if (string.charAt(index)==let||string.charAt(index)==c){
count++;
}
index++;
return count;
}
>
flounder, in the test, it tests for a lowercase letter, so i think its ok right?
also, i used a for loop and now my test succeeds in all but one area.
if the user types in Building and wants to know how many u's there are, it returns zero instead of one.
public int countLetter(char let){
char c = Character.toUpperCase(let);
int count = 0;
for(int index=0; string.charAt(index)==let||string.charAt(index)==c&&index<string.length(); index++)
count++;
return count;
}
>
awesome, thanks for the suggestion
i tested this and it works :)
public int countLetter(char let){
char c = Character.toUpperCase(let);
int count = 0;
for(int index=0;index<string.length(); index++)
if (string.charAt(index)==let||string.charAt(index)==c)
count++;
return count;
}
>