请有人帮我在元音和辅音之间增加空格。结果应该像ae bc i
public static void main(String[] args) {
String str = "aebci";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length()-1; i++) {
if ((str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u' ) &&
(str.charAt(i+1) != 'a' || str.charAt(i+1) != 'e' || str.charAt(i+1) != 'i' || str.charAt(i+1) != 'o' || str.charAt(i+1) != 'u' )) {
sb.append(" ");
}
sb.append(str.charAt(i));
}
System.out.println(sb.toString());;
}
}
最佳答案
当您的弦包含彼此靠近的元音和辅音时,您需要查找所有位置。可以使用regexp:
public static void main(String[] args) {
String str = "aebci";
Pattern pattern = Pattern.compile("([aeiou][^aeiou])|([^aeiou][aeiou])");
Matcher matcher = pattern.matcher(str);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
String group = matcher.group(); // two symbols
matcher.appendReplacement(buffer, group.charAt(0) + " " + group.charAt(1));
}
matcher.appendTail(buffer);
System.out.println(buffer.toString());
}
输出:
我
关于java - 在元音和辅音之间增加空格?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59355761/