简体   繁体   中英

how do i iterate through a string of characters to find a specific character?

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));
    }
}

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
    }

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.

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;
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM