[英]How to find out if char is number in JAVA, ONLY with string methods?
[英]How to find out which char in string is a number?
如何找出字符串中的字符是字母还是数字?
即我有一个字符串“abc2e4”,我需要找到整数,将它们平方,然后将答案放回字符串中(没有额外的字母操作),所以新字符串将是“abc4e16”。
我非常迷失在这个练习中,所以任何帮助都会很棒:D
Java 提供了一种检查字符是否为数字的方法。 为此,您可以使用Character.isDigit(char) 。
public static String squareNumbers(String input) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i); // get char at index
if (Character.isDigit(c)) // check if the char is a digit between 0-9
output.append((int) Math.pow(Character.digit(c, 10), 2)); // square the numerical value
else
output.append(c); // keep if not a digit
}
return output.toString();
}
这将逐个字符地迭代任何传递的字符串并将它找到的每个数字平方。 例如,如果 2 位数字彼此相邻,则它们将被视为单独的数字并对其进行平方,而不是一个具有多个数字的数字。
squareNumbers("10")
-> "10"
squareNumbers("12")
-> "14"
squareNumbers("abc2e4")
-> "abc4e16"
您可以使用正则表达式
public static String update(String str) {
final Pattern pattern = Pattern.compile("\\D+|\\d+");
final Matcher matcher = pattern.matcher(str);
StringBuilder buf = new StringBuilder();
int pos = 0;
while (matcher.find(pos)) {
str = matcher.group();
buf.append(Character.isDigit(str.charAt(0)) ? (int)Math.pow(Integer.parseInt(str), 2) : str);
pos = matcher.end();
}
return buf.toString();
}
我的逻辑只对个位数进行平方。
例如 - 如果您提供输入 he13llo,则输出将是 he19llo 而不是 he169llo。
Scanner in = new Scanner(System.in) ;
String str = in.next() ;
String ans = str ;
for (int i = 0 ; i < str.length() ; i++)
{
char ch = str.charAt(i) ;
if((ch - '0' >= 0) && (ch - '9' <= 0))
{
int index = i ;
int num = ch - '0' ;
int square = num * num ;
ans = ans.substring(0 ,index) + square + ans.substring(index+1) ;
}
}
System.out.println(ans) ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.