gpt4 book ai didi

java - 句子中元音的降序排列

转载 作者:行者123 更新时间:2023-12-02 05:05:56 24 4
gpt4 key购买 nike

假设我输入以下字符串:

" Hello party"

你怎么能只对链中的元音进行排序,而且是降序排列?

例如:

"Halle porty"

我尝试通过以下方式解决该问题,但是当我运行时它告诉我我有一个 ExeptionBounce 5。我该如何纠正它?我还被告知负责的线路如下:

if(cad[i].equalsIgnoreCase(vocal[j])

private String[]cad;
private String[]vocal={"a","e","i","o","u"};
private String resp="";
private String aux="":
private String []sort;
private int cont=0;


public String ordenar(String cadena)
{
cad= cadena.split("");

for(int i=0; i<cad.legth; i++)
{

for(int j=i, j<vocal.legth; j++)
{

if(cad[i].equalsIgnoreCase(vocal[j])
{

aux+=cad[i];
sort= aux.Split("");
Arrays.sort(sort);


for(int i=0; i<cad.legth; i++)
{

cad[i] = sort[k];
resp+=cad[i];

}
}
}



return resp;
}

最佳答案

您的代码甚至无法编译 - 您如何运行它?

为了回答您的问题,这里有一段代码,给定一个字符串将返回元音已排序的字符串:

    public static boolean isVowel(char c) {
return "AEIOUaeiou".indexOf(c) != -1;
}
public static String sortVowelsOnly(String input) {
if (input == null) {
return input;
}
StringBuilder result = new StringBuilder(input);

//keep track at all positions where we saw a vowel
ArrayList<Integer> vowelPositions = new ArrayList<>();
//keep track of all vowels we saw so far
ArrayList<Character> vowels = new ArrayList<>();
for (int charPosition = 0; charPosition < input.length(); charPosition++) {
char currentChar = input.charAt(charPosition);
if(isVowel(currentChar)) {
vowelPositions.add(charPosition);
vowels.add(currentChar);
}
}

Collections.sort(vowels);

//now just iterate over all positions where we saw a vowel, and populate it with the vowels from the sorted list
for(Integer vowelPosition : vowelPositions) {
char vowel = vowels.remove(0);
result.setCharAt(vowelPosition, vowel);
}
return result.toString();
}

关于java - 句子中元音的降序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56350177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com