Reputation: 1
I am having a hard time figuring out why my code will not work. I am trying to stop the output on a specific letter, but it keeps iterating through the entire string instead. This is what I have,
public static char stringIterator(String string) {
System.out.println(string);//Keep this line
char lastChar = string.charAt(string.length() - 1);
if (lastChar == 'M') {
return lastChar;
}
else if (string.length() == 1) {
return lastChar;
}
else {
return stringIterator(string.substring(0, string.length() - 2));
}
}
Upvotes: 0
Views: 1560
Reputation: 61
public String substring(int begIndex, int endIndex) - returns a new string that is a substring of the string
Parameters :
beginIndex : the begin index, inclusive.
endIndex : the end index, exclusive.
(eg): String string = "NAME"
string.substring(0, string.length() - 2) - returns "NA"
string.substring(0, string.length() - 1) - returns "NAM" . Use this, thus you will be able to subtract the last character of the string.
Iterative approach
public static char stringIterator(String string) {
char lastChar = string.charAt(0);
for(int i = string.length()-1 ;i>=0;i--) {
System.out.println(string);//Keep this line
lastChar = string.charAt(i);
if (string.length() == 1 || lastChar == 'M') {
break;
} else {
string = string.substring(0, i);
}
}
return lastChar;
}
Upvotes: 0
Reputation: 97
You might be over-thinking this... Java has very good resources for dealing with Strings, check out the docs: Java String Documentation
if (string.contains('m')){
//dostuff
}
if (string.endsWith('m')){
//dostuff
}
etc.
As for your iteration problem, you'll have to post the rest of your code, as it looks like your Loop is Calling stringIterator(String)
from somewhere outside this method.
(It's not really a stringIterator if it doesn't iterate anything)
Also this last line of code:
return stringIterator(string.substring(0, string.length() - 2));
Is recursive (calls itself)... which can cause you trouble. There's certainly uses for recursion, finding something in a 1d array is not one of those uses. Assuming your loop is working properly this could be what's preventing you from stopping the output.
Upvotes: 0
Reputation: 71
if you want to just see if it has it then you would use
string.contains('char');
if you want to traverse/iterate then
for( int i = 0; i < string.length(); i++)
if(string.at(i) == '#')
{ //whatever you want here
}
Upvotes: 2