[英]passing part of a string as a parameter
我試圖想出一個將經歷一個彈簧的循環,一旦它到達%字符,它就會將%之后的所有內容傳遞給hexToInt函數。 這就是我想出來的。
for(int x=0; x<temp.length(); x++)
{
if(temp.charAt(x)=='%')
{
newtemp = everthing after '%'
hexToInt(newtemp);
}
}
嘗試這個:
newtemp = temp.substring(x+1);
此外,您應該在找到'%'
字符后中斷。 實際上,整個代碼段可以像這樣實現(不需要為它編寫循環!):
String newtemp = temp.substring(temp.indexOf('%')+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());
試着看一下String.split()方法。
String str1 = "Some%String";
public String getString(){
String temp[] = str1.split("%");
return temp[1];
}
這種方法不需要循環。
使用'contains'進行比較和substring()方法
if(temp.contains('%')){
int index = temp.indexOf('%') + 1;
String substring = temp.substring(index, temp.length());
}
使用正則表達式而不是迭代字符串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));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.