如何有效地使用清晰的代码从带有 endWith 函数的字符串中获取数字?
How can I get number from String with endWith function effectively and with clear code?
我有像 "Test1"、"Test2"... 这样的输入,我只是试图在这些字符串中找到结束编号。我写了下面的代码,但我不喜欢它。我该如何改进这段代码?有什么建议吗?
private int getEndNumber(final String str) {
if (str.endsWith("1")) {
return 1;
} else if (str.endsWith("2")) {
return 2;
} else if (str.endsWith("3")) {
return 3;
} else if (str.endsWith("4")) {
return 4;
} else if (str.endsWith("5")) {
return 5;
} else if (str.endsWith("6")) {
return 6;
} else if (str.endsWith("7")) {
return 7;
} else {
return 0;
}
}
正则表达式是你的朋友。
Pattern p = Pattern.compile("[0-9]+$"); // This regex matches the last number
Matcher m = p.matcher(str); // Create the matcher
//If the pattern matches then we get the matching string
if(m.find()) {
result = m.group();
}
您也可以反向迭代字符串并检查字符是否为整数,但这比使用正则表达式更乏味。
这里有一篇关于正则表达式的好文章http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
你读得很透彻,几天后就忘记了一切,就像我们大多数人:-)。
一个衬垫 - return 最后一个字符:
return Integer.parseInt(str.substring(str.length() - 1)));
如果你想 return 0 也以 8
或 9
结尾,你需要向它添加一个位逻辑
@user7294900 的扩展,但多行。
如果您不想使用正则表达式。
private int getEndNumber(final String str) {
Integer num = 0;
try {
num = Integer.parseInt(str.substring(str.length() - 1)) ;
num = num >= 7 ? 0 : num;
} catch (NumberFormatException ex) {
num = 0;
}
return num;
}
我有像 "Test1"、"Test2"... 这样的输入,我只是试图在这些字符串中找到结束编号。我写了下面的代码,但我不喜欢它。我该如何改进这段代码?有什么建议吗?
private int getEndNumber(final String str) {
if (str.endsWith("1")) {
return 1;
} else if (str.endsWith("2")) {
return 2;
} else if (str.endsWith("3")) {
return 3;
} else if (str.endsWith("4")) {
return 4;
} else if (str.endsWith("5")) {
return 5;
} else if (str.endsWith("6")) {
return 6;
} else if (str.endsWith("7")) {
return 7;
} else {
return 0;
}
}
正则表达式是你的朋友。
Pattern p = Pattern.compile("[0-9]+$"); // This regex matches the last number
Matcher m = p.matcher(str); // Create the matcher
//If the pattern matches then we get the matching string
if(m.find()) {
result = m.group();
}
您也可以反向迭代字符串并检查字符是否为整数,但这比使用正则表达式更乏味。
这里有一篇关于正则表达式的好文章http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
你读得很透彻,几天后就忘记了一切,就像我们大多数人:-)。
一个衬垫 - return 最后一个字符:
return Integer.parseInt(str.substring(str.length() - 1)));
如果你想 return 0 也以 8
或 9
结尾,你需要向它添加一个位逻辑
@user7294900 的扩展,但多行。 如果您不想使用正则表达式。
private int getEndNumber(final String str) {
Integer num = 0;
try {
num = Integer.parseInt(str.substring(str.length() - 1)) ;
num = num >= 7 ? 0 : num;
} catch (NumberFormatException ex) {
num = 0;
}
return num;
}