我在这个简单的练习中遇到了麻烦。我要做的是从字符串中取出元音。
这会返回字符串中的所有元音,但我想要的是,如果有多个相同元音的字母,只需返回一个。例如,使用字符串" aaa eee iii" 应该提供" ae i" 。
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u')) {
aChar = aString.charAt(i);
System.out.print(aChar + " ");
}
}
}
答案 0 :(得分:1)
我建议将找到的每个元音添加到HashSet<Character>
,或者依次为每个元音调用aString.contains()
。您也可以使用aString.toLowerCase()
,这样您只需要检查小写元音。
答案 1 :(得分:0)
你为什么要做循环?只需检查String.IndexOf(),如果该字符存在,则打印它。
答案 2 :(得分:0)
按如下方式编辑代码:
public static void getVowels(char aChar, String aString)
{
System.out.print("Your string has the following vowels: ");
String vowels="";
for (int i = 0; i < aString.length(); i++)
{
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u'))
{
if(!vowels.contains(String.valueOf(aString.charAt(i))))
vowels+=aString.charAt(i);
}
}
for(int i=0;i<vowels.length();i++)
System.out.print(vowels.charAt(i)+" ");
}
编辑:
可替换地,
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
char vowels[]={'a','e','e','o','u'};
for (char vowel : vowels)
{
if(aString.indexOf(vowel)>=0)
{
System.out.print(vowel+" ");
}
}
}
答案 3 :(得分:0)
您需要有一个字符串,您可以在此处继续添加唯一的元音,然后检查它是否存在。以下程序将清除您的疑问。
public class TestWovel {
public static void main(String[] args) {
String vowel = "aaaeeeiiizncnzcxjswdmmnmxcuuooo";
String uniqueVowels = "";
for(int i=0;i<vowel.length();i++){
char vowelFound = vowel.charAt(i);
if((vowelFound == 'a' || vowelFound == 'e' || vowelFound == 'i' || vowelFound == 'o' || vowelFound == 'u') && (uniqueVowels.indexOf(vowelFound) == -1)){
uniqueVowels+=vowelFound;
}
}
System.out.println(uniqueVowels);
}
}
答案 4 :(得分:-1)
您可以使用索引为ASCII码的整数数组。当您看到元音时,请检查其在数组中的计数。如果计数为0,则打印元音并增加计数。例如,&#39; a&#39;将存储在arr [97]:
中public static void getVowels(String aString) {
int[] arr = new int[128];
char c;
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
c = aString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
if (arr[c] == 0) {
System.out.print(aString.charAt(i) + " ");
arr[c]++;
}
}
}
}