有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将字符串中的字符替换为整数

    String str="b5l*a+i";//trying to replace the characters by user input (integer)
    StringBuffer sb=new StringBuffer(str);
    for(int i=0;i<sb.length();i++)
    {
        for(int j='a';j<='z';j++)
        {
            if(sb.charAt(i)==j)
            {
                System.out.println("Enter value for "+j);
                int ip=sc.nextInt();
                char temp=(char)ip;
                //here how to replace the characters by int????

            }
        }
    }

/*最后它看起来像输入值b 4输入值a 5输入值i 6输出为451*5+6*/


共 (3) 个答案

  1. # 1 楼答案

    根据凯文·安德森的评论修改代码,这似乎符合你的要求:

    Scanner sc = new Scanner(System.in);
    String str="b5l*a+i";
    StringBuffer sb=new StringBuffer(str);
    for(int i=0;i<sb.length();i++)
    {
        for(int j='a';j<='z';j++)
        {
            if(sb.charAt(i)==j)
            {
                System.out.println("Enter value for "+(char)j);
                int ip=sc.nextInt();
                sb.deleteCharAt(i);
                sb.insert(i, ip);
            }
        }
    }
    

    我还可以推荐这个行为类似的代码吗

    Scanner sc = new Scanner(System.in);
    String str="b5l*a+i";
    StringBuffer sb=new StringBuffer(str);
    for(int i=0;i<sb.length();i++)
    {
        char original = sb.charAt(i);
        if(original >= 'a' && original <= 'z')
        {
            System.out.println("Enter value for "+original);
            int ip=sc.nextInt();
            sb.deleteCharAt(i);
            sb.insert(i, ip);
        }
    }
    

    它应该更高效,因为它不必在字符之间循环

    编辑

    在看到@Sebastien的优秀答案,并应用了我自己的一些更改之后,我相信下面的解决方案比上面的解决方案更好,如果它符合您的项目限制的话

    Scanner sc = new Scanner(System.in);
    String str = "b5l*a+i";
    Matcher matcher = Pattern.compile("[a-z]").matcher(str);
    StringBuilder sb = new StringBuilder(str);
    while (matcher.find())
    {
        System.out.println("Enter value for " + matcher.group());
        int ip = sc.nextInt();
        sb.setCharAt(matcher.start(), Character.forDigit(ip, 10));
    }
    

    以下是更好的:

    • 使用正则表达式进行模式匹配。这样,您就不需要手动搜索String的每个字符并检查它是否是一个字母,然后决定如何处理它。你可以让Matcher为你做这件事。正则表达式[a-z]的意思是“从a到z的范围内只有一个字符。matcher.find()方法每次在该表达式通过String时为该表达式找到一个新的匹配项时返回true,当没有更多字符时返回false。然后,matcher.group()从过去的find()操作中获取字符(作为String,但这对我们来说并不重要)matcher.start()获取匹配的索引(这些方法被命名为start()end(),因为一个典型的匹配将不止一个字符,并且有一个开始和结束索引,但对我们来说只有start()重要)
    • 切换到StringBuilderStringBuilder被认为是{}设计目的的更新实现。通常最好使用StringBuilder,除非你需要你的应用程序是线程安全的(你不需要,除非你确定你确实需要它)。在我们的例子中,它还通过提供setCharAt方法使操作变得更加容易,该方法正是我们需要做的。现在我们可以在char的索引中插入我们想要更改的字符(这是Matcher方便地提供给我们的),以及我们从输入中获得的新字符。我们必须首先使用Character类的方便静态方法forDigit从int中生成一个字符。第一部分是我们从输入中读取的数字,第二位是基数,它需要知道基数来确定数字的有效性(例如,在base-10中,输入10将无效,但在base-16中,十六进制,它将返回'a'),在我们的示例中,我们将其设置为10,因为base-10是最常见的英语数字系统。如果输入无效(即多个10进制数字,如10,或小于0),它将返回一个空字符,因此您可能希望将其从forDigit参数中弹出,首先检查它是否为空,并相应地处理输入,如下所示:

      char ipChar = Character.forDigit(ip, 10);
      if (ipChar == '\u0000') throw new MyCustomNotADigitException("error message");
      sb.setCharAt(matcher.start(), ipChar);
      
  2. # 2 楼答案

    String str = "muthu", str1 = "";
            int n = 5;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == 'u') {
                    str1 = str1 + n;
                } else
                    str1 = str1 + str.charAt(i);
            }
    
  3. # 3 楼答案

    用正则表达式

    你应该使用正则表达式,它更优雅,功能更强大。例如,在不更改代码行的情况下,可以使用组成多个字母的变量名

    范例

    Scanner sc = new Scanner(System.in);
    String str = "b5l*a+i";
    
    // This pattern could be declared as a constant
    // It matches any sequence of alpha characters
    Pattern pattern = Pattern.compile("[a-zA-Z]+");
    
    Matcher matcher = pattern.matcher(str);
    
    StringBuffer result = new StringBuffer();
    
    // For each match ...
    while(matcher.find()) {
        // matcher.group() returns the macth found
        System.out.println("Enter value for "+ matcher.group());
    
        Integer input = sc.nextInt();
    
        // ... append the parsed string with replacement of the match ...
        matcher.appendReplacement(result, input.toString());
    }
    
    // ... and don't forget to append tail to add characters that follow the last match 
    matcher.appendTail(result);
    
    System.out.println(result);