【问题标题】:Copying characters in a string复制字符串中的字符
【发布时间】:2013-11-21 12:10:12
【问题描述】:

我正在尝试从字符串中删除每个数字,然后复制该数字之后的字母。 例如,字符串4a2b 应该输出aaaabb。 到目前为止,我的代码如下所示:

Scanner scan= new Scanner(System.in);
    String s = scan.nextLine();
    String newString = s.replace(" ", "");
    newString=newString.replaceAll("\\W+", "");
    newString=newString.replaceAll("\\d+", "");
    System.out.println(newString);

是否可以使用 regex 和 replaceAll 来做到这一点?

【问题讨论】:

    标签: java regex replace copy


    【解决方案1】:

    试试,

       String newString = "4a2b";
        String num = "";
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < newString.length(); i++) {
            char ch = newString.charAt(i);
    
            if (Character.isDigit(ch)) {
                num += ch;
    
            } else if (Character.isLetter(ch)) {
                if (num.length() > 0) {
                    for (int j = 0; j < Integer.parseInt(num); j++) {
                        res.append(ch);
                    }
                }
                num="";
            }
        }
        System.out.println(res);
    

    【讨论】:

    • 这将导致“4a2b”变成“aaab”,这不是 OP 想要的。
    • 还是不行。 OP希望“4a”变成“aaaa”,“2b”变成“bb”。
    • 应该补充一点,它应该适用于每个字母,而不仅仅是 a 和 b。
    【解决方案2】:

    试试这个:

    public static void main(String[] args)
    {
        String str = "ae4a2bca";
        Matcher m = Pattern.compile("(\\d+)(.)").matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find())
        {
            m.appendReplacement(sb, times("$2", Integer.parseInt(m.group(1))));
        }
        m.appendTail(sb);
        System.out.println(sb.toString());
    }
    
    private static String times(String string, int t)
    {
        String str = "";
        for (int i = 0; i < t; ++i) str += string;
        return str;
    }
    

    【讨论】:

    • 它也是使用正则表达式作为OP请求的那个。
    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多