我是 Java 的新手,我在 codeforces.com
中发现了一个关于从字符串中删除所有元音并在每个辅音前添加点 (.) 的问题。我已经找到了如何删除所有元音,但还没有找到如何在每个辅音前添加点。请帮助我 :) 谢谢
public class Stringprob{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
String word;
word = s.next();
word = word.replaceAll("[aeiouyAEIOUY]","");
//the problem says that 'Y' is a vowel too
word = insert("[^aeiouyAEIOUY]", ".");
//here is where I lost it all
System.out.println(word);
}
}
抱歉,代码真的很乱,我是 Java 新手。
最佳答案
你可以使用capture group()
和$1
作为替换
1.) 删除所有元音 [aeiouyYAEIOU]
2.) 应用步骤 1 后将只剩下辅音,因此,使用 ([a-zA-Z])
捕获每个字符并将其替换为 .$1
其中 .
是一个点,$1
是字符本身
注意: [a-zA-Z]
在性能方面会更高效,因为这只会捕获字符,如 ([^aeiouyAEIOUY] )
将匹配元音以外的任何内容,这意味着它还可以匹配特殊字符和数字,如 @#$%^&*12346
。
word = word .replaceAll("[aeiouyYAEIOU]","");
word = word.replaceAll("([a-zA-Z])", ".$1");
或者用特殊字符和数字来匹配和添加.
word = word .replaceAll("[aeiouyYAEIOU]","");
word = word.replaceAll("([^aeiouyAEIOUY])", ".$1");
([^aeiouyAEIOUY])
:捕获所有辅音并使用替换为 .$1
其中 $1
代表捕获的辅音
[^aeiouyAEIOUY]
: ^
表示不在[]
String s = "abcdefghijklmnopqrstuvwxyzAEIOUY";
// replace all vowels
s = s.replaceAll("[aeiouyYAEIOU]","");
s = s.replaceAll("([a-zA-z])", ".$1");
System.out.println(s);
输出:
.b.c.d.f.g.h.j.k.l.m.n.p.q.r.s.t.v.w.x.z
仅供引用,您也可以在一行中执行此操作,您可以在第一个 replaceAll
函数的输出上应用第二个 replaceAll
函数
s = s.replaceAll("[aeiouyYAEIOU]","").replaceAll("([^aeiouyAEIOUY])", ".$1");
关于java - 如何在字符串中的每个辅音之前添加 '.'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41636659/