[英]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. 我试图想出一个将经历一个弹簧的循环,一旦它到达%字符,它就会将%之后的所有内容传递给hexToInt函数。 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: 如果你需要在'%'字符的LAST实例之后将字符串分解为字符串的结尾(假设字符串中有多个'%'字符),则可以使用以下命令:
int index = temp.lastIndexOf('%') + 1;
String substring = temp.substring(index, temp.length());
Try to have a look at the String.split() method. 试着看一下String.split()方法。
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 使用'contains'进行比较和substring()方法
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. 使用正则表达式而不是迭代字符串char-by-char会更容易解析。 Something like
(.*)%([0-9a-fA-F]+)
could also validate the hexadecimal token. 像
(.*)%([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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.