【问题标题】:(hello-> h3o) How to replace in a String the middle letters for the number of letters replaced(hello-> h3o) 如何在字符串中替换中间字母为替换的字母数
【发布时间】:2019-10-15 12:25:13
【问题描述】:

我需要构建一个接收字符串的方法,例如“骑大象真的很有趣!”。并返回另一个类似的字符串,在这个例子中返回应该是:“e6t-r3s are r4y fun!”。 (因为 e-lephan-t 有 6 个中间字母,r-ide-s 有 3 个中间字母等等)

为了得到这个回报,我需要在每个单词中替换中间字母,以替换替换的字母数量,保持不变,所有内容都不是字母,而是每个单词的第一个和最后一个字母。

目前我尝试使用正则表达式将接收到的字符串拆分为单词,并将这些单词保存在字符串数组中,我还有另一个 int 数组,其中保存了中间字母的数量,但我没有不知道如何将数组和符号连接成正确的字符串以返回

    String string="elephant-rides are really fun!";
String[] parts = string.split("[^a-zA-Z]");
int[] sizes = new int[parts.length];
int index=0;

for(String aux: parts)
{

    sizes[index]= aux.length()-2;
    System.out.println( sizes[index]);
    index++;

}

【问题讨论】:

  • 你为什么不直接用空格和破折号分割,然后取单词长度-2?

标签: java regex string


【解决方案1】:

你可以使用

String text = "elephant-rides are really fun!";
Pattern r = Pattern.compile("(?U)(\\w)(\\w{2,})(\\w)");
Matcher m = r.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, m.group(1) + m.group(2).length() + m.group(3));
}
m.appendTail(sb); // append the rest of the contents
System.out.println(sb);
// => e6t-r3s are r4y fun!

Java demo

这里,(?U)(\\w)(\\w{2,})(\\w) 匹配任何将其捕获到组 1 中的 Unicode 单词 char,然后将任何 2 个或更多单词 char 捕获到组 2 中,然后将单个单词 char 捕获到组 3 中,在 .appendReplacement 方法中,第二组内容被“转换”成它的长度。

Java 9+:

String text = "elephant-rides are really fun!";
Pattern r = Pattern.compile("(?U)(\\w)(\\w{2,})(\\w)");
Matcher m = r.matcher(text);
String result = m.replaceAll(x -> x.group(1) + x.group(2).length() + x.group(3));
System.out.println( result );
// => e6t-r3s are r4y fun!

【讨论】:

    【解决方案2】:

    按照您给我们的指示,这就足够了:

    String [] result = string.split("[\\s-]");
    for (int i=0; i<result.length; i++){
        result[i] = "" + result[i].charAt(0) + ((result[i].length())-2) + result[i].charAt(result[i].length()-1);
    }
    

    根据您的输入,它会创建数组 [ "e6t", "r3s", "a1e", "r4y", "f2!" ]

    它甚至可以使用一两个大小的单词,但它给出的结果如下:

    输入:I am a small;输出:[ "I-1I", "a0m", "a-1a", "s3l" ]

    同样,根据您给我们的指示,这是合法的。

    希望我能帮上忙!

    【讨论】:

      猜你喜欢
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 2016-02-01
      • 2019-02-06
      相关资源
      最近更新 更多