传递一部分字符串作为参数

时间:2013-08-25 19:50:51

标签: java

我试着想出一个将经历一个弹簧的循环,一旦它到达%字符,它就会将%之后的所有内容传递给hexToInt函数。这就是我想出来的。

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

5 个答案:

答案 0 :(得分:7)

试试这个:

newtemp = temp.substring(x+1);

此外,您应该在找到'%'字符后中断。实际上,整个代码片段可以像这样实现(不需要为它编写循环!):

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

答案 1 :(得分:1)

您可以将原始字符串的子字符串从'%'的第一个索引带到结尾并完成相同的操作:

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

如果你需要在字符串末尾的'%'字符的LAST实例之后断开字符串(假设字符串中有多个'%'字符),你可以使用以下内容:

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

答案 2 :(得分:0)

尝试查看String.split()方法。

String str1 = "Some%String";

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

这种方法不需要循环。

答案 3 :(得分:0)

使用'contains'进行比较和使用substring()方法

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

答案 4 :(得分:0)

使用regexp而不是迭代字符串char-by-char会更容易解析。 像(.*)%([0-9a-fA-F]+)这样的东西也可以验证十六进制标记。

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));
    }
}
相关问题