简体   繁体   English

如何找出字符串中的哪个字符是数字?

[英]How to find out which char in string is a number?

How to find out if the char in string is a letter or a number?如何找出字符串中的字符是字母还是数字?

Ie I have a string "abc2e4", I need to find the ints, square them, and put the answer back in the string (no extra operations with the letters), so the new string would be "abc4e16".即我有一个字符串“abc2e4”,我需要找到整数,将它们平方,然后将答案放回字符串中(没有额外的字母操作),所以新字符串将是“abc4e16”。

Im incredibly lost with this exercise, so any help would be great :D我非常迷失在这个练习中,所以任何帮助都会很棒:D

Java provides a method to check whether a character is a digit. Java 提供了一种检查字符是否为数字的方法。 For this you can use Character.isDigit(char) .为此,您可以使用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();
}

This will iterate any passed string character by character and square each digit it finds.这将逐个字符地迭代任何传递的字符串并将它找到的每个数字平方。 If for example 2 digits are right next to each other they will be seen as individual numbers and squared each and not as one number with multiple digits.例如,如果 2 位数字彼此相邻,则它们将被视为单独的数字并对其进行平方,而不是一个具有多个数字的数字。

squareNumbers("10") -> "10" squareNumbers("10") -> "10"

squareNumbers("12") -> "14" squareNumbers("12") -> "14"

squareNumbers("abc2e4") -> "abc4e16" squareNumbers("abc2e4") -> "abc4e16"

You can do it using Regular Expression您可以使用正则表达式

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();
}

My logic only squares single digit numbers.我的逻辑只对个位数进行平方。

For eg - if you provide input he13llo, the output would be he19llo and not he169llo.例如 - 如果您提供输入 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM