我编写了一段代码来反转给定字符串中元音的顺序,但我还需要保持元音大写在字符串中的原始位置。例如,输入:Java Is Fun
输出:Juvi As Fan
而不是 JuvI as Fan
。
这是我到目前为止的代码,当前输出 JuvI 作为 Fan
:
static boolean isVowel(char c)
{
return (c == 'a' || c == 'A' || c == 'e'
|| c == 'E' || c == 'i' || c == 'I'
|| c == 'o' || c == 'O' || c == 'u'
|| c == 'U');
public static String reverseVowels(String text)
{
int index = 0;
char[] str = text.toCharArray();
String vowel = "";
for (int i = 0; i < str.length; i++)
{
if (isVowel(str[i]))
{
index++;
vowel += str[i];
}
}
for (int i = 0; i < str.length; i++)
{
if (isVowel(str[i]))
{
str[i] = vowel.charAt(--index);
}
}
return String.valueOf(str);
最佳答案
我会记录所有大写字母(如果字符串中大写字母多于小写字母,则记录小写字母),例如。
List<Integer> capitalLetters = new ArrayList<>(); // Positions of capital letters.
for (int i = 0; i < text.length(); i++) {
if (Character.isUpperCase(text.charAt(i))) {
capitalLetters.add(i);
}
}
text = text.toLowerCase();
int index = 0;
char[] str = text.toCharArray();
String vowel = "";
for (int i = 0; i < str.length; i++) {
if (isVowel(str[i])) {
index++;
vowel += str[i];
}
}
for (int i = 0; i < str.length; i++) {
if (isVowel(str[i])) {
str[i] = vowel.charAt(--index);
}
}
// Recapitalise.
for (int pos : capitalLetters) {
str[pos] = Character.toUpperCase(str[pos]);
}
return str;
我还将您的元音检查功能更改为:
c = Character.toLowerCase(c);
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
避免检查大写字母
关于for循环中的Java特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60197207/