2013-08-25 155 views
3

即时尝试想出一个循环,将通过一个春天,一旦它到达%字符,它会传递所有后面的%到hexToInt函数。这是我想出来的。传递一个字符串的一部分作为参数

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

try with temp.substring(); – nachokk

+0

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#substring(int) – FDinoff

+1

还有http://docs.oracle.com/javase/7/docs/ api/java/lang/String.html#indexOf(int) –

回答

7

试试这个:

newtemp = temp.substring(x+1); 

此外,'%'字符后发现你应该打破。事实上,整个片段可以这样来实现(没有必要为它编写一个循环!):

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

+1,不需要重新发明轮子。 –

+0

谢谢。你还可以帮我用代码将字符串中最后两个字符的“+”前面加上。 – user1896464

+0

我有这个,但theres错误。 StringBuffer下的红线 word = StringBuffer(word).insert(word.length() - 2,“+”)。toString(); – user1896464

0

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

String str1 = "Some%String"; 

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

该方法不需要循环。

0

使用“包含”进行比较和子()方法

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

不需要:他比较*字符*(注意单引号)。 –

+0

谢谢..让我改进答案 –

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()); 
0

使用正则表达式解析会更容易,而不是迭代字符串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)); 
    } 
} 
相关问题