Simple Pig Latin

Simple Pig Latin

创建时间: November 7, 2021 3:37 PM
最后编辑时间: November 7, 2021 4:33 PM
标签: 声明式编程, 字符串, 正则
状态: 已完成
等级: 5 kyu
网址: https://www.codewars.com/kata/520b9d2ad5c005041100000f/train/java

Details

Move the first letter of each word to the end of it, then add “ay” to the end of the word. Leave punctuation marks untouched.

把每个单词的第一个字母移到它的末尾,然后在单词末尾加上“ay”。不要动标点符号。

Examples

pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
pigIt('Hello world !');     // elloHay orldway !

解法

我的解法

使用正则表达式进行编写

import java.util.regex.*;
public class PigLatin {
    public static String pigIt(String str) {
      //正则匹配的标准写法
      Matcher m=Pattern.compile("\\w+").matcher(str);
      StringBuffer sb=new StringBuffer();
      //appendReplacement和appendTail的模板写法,
      //替换匹配到的字符串,生成新的StringBuffer
      while(m.find()){
        StringBuilder s=new StringBuilder(m.group());
        s.append(s.charAt(0)).append("ay");
        m.appendReplacement(sb,s.substring(1));
      }
      m.appendTail(sb);
      return sb.toString();
    }
}

优秀解法

使用字符串自带的replaceAll 方法进行正则替换,

这里用到了分组匹配,以Hello为例,\w 匹配H,\w*匹配ello,

$1指第一组,$2指第二组,$2$1ay指将一二组交换,并在结尾添加ay

public class PigLatin {
    public static String pigIt(String str) {
        return str.replaceAll("(\\w)(\\w*)", "$2$1ay");
    }
}

查看replaceAll 的源码

public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

发现字符串的replaceAll 使用的是正则的replaceAll ,继续追溯

public String replaceAll(String replacement) {
        reset();
        boolean result = find();
        if (result) {
            StringBuffer sb = new StringBuffer();
            do {
                appendReplacement(sb, replacement);
                result = find();
            } while (result);
            appendTail(sb);
            return sb.toString();
        }
        return text.toString();
    }

使用的是appendReplacement搭配appendTail ,继续查看appendReplacement

public Matcher appendReplacement(StringBuffer sb, String replacement) {
......
if (nextChar == '$') {
......
// Append group
                if (start(refNum) != -1 && end(refNum) != -1)
                    result.append(text, start(refNum), end(refNum));

因此,可以使用$+数字来进行分组匹配,类似m.group(int)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值