简体   繁体   中英

Java: how do icheck if a certain character is within a string, then print out the position it is in relative to the string?

What I am trying to do, is create a method, that has a string and a character as parameters, the method then takes the string and searches for the given character. If the string contains that character, it returns an array of integers of where the character showed up. Here is what I have so far:

public class Sheet {
public static void main(String[] args) {
    String string = "bbnnbb";
    String complete = null;
    //*******
    for(int i = 0; i < string.length(); i++){
        complete = StringSearch(string,'n').toString();
    }
            //********
}

public static int[] StringSearch(String string, char lookfor) {
    int[]num = new int[string.length()];
    for(int i = 0; i < num.length; i++){
        if(string.charAt(i)== lookfor){
            num[i] = i;
        }
    }
    return num;
}

}

The method works fine, and returns this:

0
0
2
3
0
0

What I am trying to do, is make those into 1 string so it would look like this "002300". Is there any possible way of doing this? I have tried to do it in the starred area of the code, but I have had no success.

just do

StringBuffer strBuff = new StringBuffer();
for(int i = 0; i<str.length(); i++)
{
    if(str.charAt(i) == reqChar)
    {
        strBuff.append(str.charAt(i));
    }
    else
    {
        strBuff.append('0');
    }
}
return str.toString();

Just add the result to the existing string with the += operator

String complete = "";
for(...)
    complete += StringSearch(string,'n').toString();

Updated with StringBuilder for better practices.

public static String StringSearch(String string, char lookfor) {
    StringBuilder sb = new StringBuilder();

    for(int i = 0; i < string.length; i++){
        if(string.charAt(i) == lookfor)
            sb.append(i);
        else
            sb.append("0");
    }
    return sb.toString();
}

Then you can just call it once, without a for loop. Not sure why you call it for every character in the string.

complete = StringSearch(string,'n');

I would just use java's regex library, that way it's more flexible (eg if you want to look for more than just a single character). Plus it's highly optimized.

StringBuilder positions = "";

Pattern pattern = Pattern.compile(string);
Matcher matcher = pattern.matcher(lookfor);
while(matcher.find()){
    positions.append(matcher.start());
}

return positions;

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