[英]How do I test if a string begins with a vowel using an iterator
I have written a program using an iterator for the first time. 我是第一次使用迭代器编写程序。 I have an array list of strings and I have printed them using the hasNext and next method.
我有一个字符串数组列表,并使用hasNext和next方法打印了它们。 I am now trying to go backwards using the previous method and while doing so I am suppose to check each element and if it starts with a vowel I nedd to delete it from the list.
我现在尝试使用先前的方法向后移动,同时这样做是为了检查每个元素,如果它以元音开头,则我将其从列表中删除。 Here is the piece of code that I am having trouble with.
这是我遇到麻烦的代码。
while (iterator.hasPrevious())
{
String s = iterator.previous();
if (s.startsWith("a"))
{
iterator.remove();
}
System.out.print(" "+ s);
}
Any help would be greatly appreciated! 任何帮助将不胜感激!
String vowels = "aeiou";
String testString = ... // Iterator String
if (vowels.indexOf(Character.toLowerCase(testString.charAt(0))) != -1) {
... // Start char is vowel
}
To check whether a String
starts with a vowel, you can use regular expressions. 要检查
String
是否以元音开头,可以使用正则表达式。
For instance: 例如:
String[] input = {"abc", "def", "ghi"};
for (String s: input) {
System.out.printf("\"%s\" starts with a vowel? %b%n", s, s.matches("(?i)^[aeiouy].*$"));
}
Output 输出量
"abc" starts with a vowel? true
"def" starts with a vowel? false
"ghi" starts with a vowel? false
In your case... 就你而言...
The method startsWith
only takes a literal, so it's not what you want. startsWith
方法仅需要一个文字,因此不是您想要的。
Instead, you could use a constant Pattern
in your class, such as: 相反,您可以在类中使用常量
Pattern
,例如:
static final Pattern STARTS_WITH_VOWEL = Pattern.compile("^[aeiouy]", Pattern.CASE_INSENSITIVE);
Then in your loop, you could use: 然后在循环中,您可以使用:
if (STARTS_WITH_VOWEL.matcher(s).find()) {
...
}
A readable way to do it would be to have a list of all the vowels 可读的方法是列出所有元音
Collection<Character> vowels = new HasSet<~>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
Then what you could do is 那你能做的就是
if (vowels.conatins(Character.toLowerCase(s)))
{
iterator.remove();
}
just change the if to include more conditions 只需更改是否包含更多条件
if (s.startsWith("a") || if (s.startsWith("A"))...) 如果(s.startsWith(“ a”)||如果(s.startsWith(“ A”))...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.