我是C程序员而不是Java程序员。我不知道Java中有哪些方法可用,哪些方法没有。几个小时以来我一直在努力。
它是一个大项目的一部分。我有一根弦,我需要元音,辅音和音符。数字出现在字符串中。
string s = "asdf";
char[] charArr = s.toLowerCase().toCharArray();
for(int i=0;i<s.length();i++)
{
if( charArr[i] == 'a' || charArr[i] == 'e' || charArr[i] == 'i' || charArr[i] == 'o' || charArr[i] == 'u')
{
// stuff here
}
}
但这看起来不像Java代码。我仍然在考虑C.我想让它看起来像Java。我有什么方法可以使用吗?
答案 0 :(得分:5)
这是一种可能性,非常易读......: - )
至少,为了便于阅读,你应该像ifVowel,isConsonant这样的方法提取if-test。
public class TestStringIteration {
private static final HashSet<Character> VOWELS = new HashSet<Character>(
Arrays.asList('a', 'e', 'i', 'o', 'u'));
private static final HashSet<Character> CONSONANTS = new HashSet<Character>(
Arrays.asList('b', 'c')); // Add more letters :-)
void stringTest(String s) {
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
// This is a digit
} else if (isVowel(c)) {
// This is a vowel
} else if(isConsonant(c)) {
// This is a consonant
}
}
}
private static boolean isVowel(char c) {
return VOWELS.contains(c);
}
private static boolean isConsonant(char c) {
return CONSONANTS.contains(c);
}
}
编辑:isVowel
和isConsonant
静态
答案 1 :(得分:3)
老实说,你的方法没有错。无论您需要迭代所有角色。如果您不关心索引值,可能需要使用增强的for循环。
for(char c : s.toCharArray()){
if(c == 'a' || c == 'e' || ...){
// stuff
}
}
答案 2 :(得分:2)
在这种情况下,Java代码与C
没有太大区别private enum CharType {VOWEL, CONSONANT, NUMBER, OTHER;}
static CharType getType(final char ch) {
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
switch (ch) {
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
return CharType.VOWEL;
default:
return CharType.CONSONANT;
}
} else if (ch >= '0' && ch <= '9') {
return CharType.NUMBER;
}
return CharType.OTHER;
}
答案 3 :(得分:1)
as Javaish as possible; - )
String s = "asdf".toLowerCase();
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
// stuff here
}
}
您是否正在将C代码重写为Java?
答案 4 :(得分:0)
只有几个指针(没有双关语:D)爪子。
通常在Java中我们倾向于使用String
而不是char[]
,我们广泛使用String类中可用的方法。实用程序类中还有其他有用的方法,例如Apache Commons Lang lib http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html
答案 5 :(得分:0)
绝对没有理由为这类问题使用普通for循环:
String s = "asdf";
for(char c : s.toLowerCase()) {
if( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
// stuff here
}
}
答案 6 :(得分:0)
是什么让你觉得你的代码不是java?它是,并且比重复使用String.charAt
更有效。如果要在随机位置访问字符,将字符串转换为char[]
是个好主意,前提是字符串不会太长。
如果您要按顺序访问单个字符,但有更好的解决方案,例如StringReader
。
我还建议将你的逻辑分开一点。例如,制作isVowel(char c)
方法。
答案 7 :(得分:0)
如果您想使用Java API使其看起来更像javaish,您可以尝试使用正则表达式的方法:
String input = "foo bar fun for vowels";
Pattern p = Pattern.compile("[aAeEiIoOuU]");
Matcher m = p.matcher(input);
while ( m.find() ) {
// stuff here with my example output
System.out.println("Index: " + m.start() + " vowel was: " + input.substring(m.start(), m.end()));
}
但是您的代码没有任何问题。你的性能比我的高。这只是为了看起来。