所以我为我的AP计算机科学课程编写了一些代码,但我的老师要求我不要在我的代码中使用char或token。我有一个特别的代码,我需要一个替代(非char)版本。
// returns the first nonzero digit of a string, 0 if no such digit found
public static int firstDigitOf(String token) {
for (char ch : token.toCharArray()) {
if (ch >= '1' && ch <= '9') {
return ch - '0';
}
}
return 0;
}
所以,请帮助我。这不是作业,它是大型项目的一部分,因此特别需要完整的代码行。
or (char ch : token.toCharArray()) {
这是我最麻烦的事情,我只是不知道另一种写这个的方式。
答案 0 :(得分:2)
你可以用这个
String token = "helo100s23h04dsd sdksjdksa";
token = token.replaceAll("[^1-9]", "");
// in this case token value will be -> 1234, and the first none zero digit is 1
if (token.length() <= 0) {
// if there is no numbers in token larger than 0
return 0;
} else {
return Character.getNumericValue(token.charAt(0));
}
答案 1 :(得分:1)
如果输入字符串是全部数字,这将起作用:
public static int firstDigitOf(String digits) {
if (digits.length() == 0)
return 0;
int firstDigit = Integer.parseInt(digits.substring(0, 1));
if (firstDigit > 0)
return firstDigit;
return firstDigitOf(digits.substring(1));
}
迭代版本:
public static int firstDigitOf(String digits) {
int firstDigit = 0;
while (digits.length() != 0) {
firstDigit = Integer.parseInt(digits.substring(0, 1));
if (firstDigit > 0)
break;
digits = digits.substring(1);
}
return firstDigit;
}
如果字符串可能包含非数字,则需要执行以下操作:
public static int firstDigitOf(String token) {
if (token.length() == 0)
return 0;
try {
int firstDigit = Integer.parseInt(token.substring(0, 1));
if (firstDigit > 0 && firstDigit < 10)
return firstDigit;
} catch (NumberFormatException e) {
}
return firstDigitOf(token.substring(1));
}
答案 2 :(得分:0)
我想出了以下内容:
public Integer firstDigitOf(String s) {
s=s.replaceAll("[^1-9]","");
return (s.isEmpty())?0:Integer.parseInt(s.substring(0,1));
}
只需替换所有非数字内容,并给出0或第一位数字。
答案 3 :(得分:0)
本着矫枉过正的精神,这是一个正则表达式版本。请注意,没有使用直接使用char - 它都是使用String完成的。
private static Pattern nonZeroDigit = Pattern.compile("[123456789]");
public static int firstDigitOf(String token) {
Matcher digitMatcher = nonZeroDigit.matcher(token);
if (digitMatcher.find()) {
return Integer.parseInt(digitMatcher.group());
} else {
return 0;
}
}