【问题标题】:Replacing the character in a String by integer用整数替换字符串中的字符
【发布时间】:2017-07-09 07:30:25
【问题描述】:
    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????

            }
        }
    }

/* 最后它看起来像 enter value b 4 enter value a 5 enter value i 6 输出是 451*5+6 */

【问题讨论】:

标签: java string


【解决方案1】:

使用正则表达式

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

示例

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

【讨论】:

  • 你会想在循环之后appendTail()。在本例中无关紧要,但如果String 以数字结尾则很重要,因为否则您将丢失最后一个字母之后的任何内容。不过,我喜欢这个解决方案!
  • 确实你是对的,appendTail(...) 不见了。我会编辑我的帖子。这应该经过单元测试才能做得很好。
【解决方案2】:

通过跟进 Kevin Anderson 的评论来获取您的代码并对其进行调整,这似乎可以满足您的需求:

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 和 @987654331 时找到该表达式的新匹配项时都会返回 true @ 当没有更多的时候。然后,matcher.group() 从过去的find() 操作中获取字符(作为String,但这对我们来说无关紧要)。matcher.start() 获取匹配的索引(方法被命名为start()end(),因为一个典型的匹配将有多个字符并且有一个开始和结束索引,但只有start() 对我们很重要。
  • 切换到StringBuilderStringBuilder 被认为是 StringBuffer 的新实现。通常首选使用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);
    

【讨论】:

  • 没问题,很高兴能帮上忙。如果下次不想等答案,Java类库中每个类的具体方法列表,以及每个方法的作用,可以参考here.,非常有用。
【解决方案3】:
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);
        }

【讨论】:

  • 请解释为什么这会回答原来的问题。
猜你喜欢
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 2013-05-03
  • 2015-09-25
  • 1970-01-01
  • 2021-09-27
  • 2012-04-26
相关资源
最近更新 更多