简体   繁体   中英

passing part of a string as a parameter

im trying come up with a loop that will go through a spring and as soon as it gets to the % character, it will pass everything that comes after the % to the hexToInt function. this is what i came up with.

for(int x=0; x<temp.length(); x++)
    {
        if(temp.charAt(x)=='%')
        {
            newtemp = everthing after '%'
            hexToInt(newtemp);
        }
    }

Try this:

newtemp = temp.substring(x+1);

Also, you should break after the '%' character is found. In fact, the whole snippet could be implemented like this (there's no need to write a loop for it!):

String newtemp = temp.substring(temp.indexOf('%')+1);

You can just take a substring of the original string from the first index of '%' to the end and accomplish the same thing:

int index = temp.indexOf('%') + 1;
String substring = temp.substring(index, temp.length());

If you need to break the string after the LAST instance of a '%' character to the end of the string (assuming there are more than one '%' character in the string) you can use the following:

int index = temp.lastIndexOf('%') + 1;
String substring = temp.substring(index, temp.length());

Try to have a look at the String.split() method.

String str1 = "Some%String";

public String getString(){
    String temp[] = str1.split("%");
    return temp[1];
}

No loop is needed for this approach.

Use 'contains' for comparison and substring() method

if(temp.contains('%')){
int index = temp.indexOf('%') + 1;
String substring = temp.substring(index, temp.length());
}

It would be easier to parse using a regexp instead of iterating the string char-by-char. Something like (.*)%([0-9a-fA-F]+) could also validate the hexadecimal token.

public static void main(String[] args) {
    String toParse = "xxx%ff";

    Matcher m = Pattern.compile("(.*)\\%([0-9a-fA-F]+)").matcher(toParse);

    if(m.matches()) {
        System.out.println("Matched 1=" + m.group(1) + ", 2=" + Integer.parseInt(m.group(2), 16));
    }
}

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