使用循环从句子中追加特定字符

时间:2012-08-17 16:58:01

标签: java

我想知道是否可以通过将辅音附加到StringBuilder变量的正确方法获得一些帮助。

就目前而言,它成功查找并计算了句子中发现的元音数量,但是,我在创建排除它们的新变量时遇到了麻烦。

    char[] vowels = {'a', 'e', 'i', 'o', 'u'};
    int vowelCount = 0;
    String defParagraph = "This is an example sentence.";
    StringBuilder sbParagraph = new StringBuilder(defParagraph);
    StringBuilder vowParagraph = new StringBuilder("");

    System.out.print("Characters: " + sbParagraph.length());

    for (int i = 0; i < sbParagraph.length(); i++) {
        for (int j = 0; j < vowels.length; j++) {
            if (sbParagraph.toString().toLowerCase().charAt(i) == vowels[j]) {
                vowelCount++;
            }
        }
    }

我尝试在循环中添加vowParagraph.append(sbParagraph.charAt(i),但它给了我新字符串中相同字符的倍数。我还考虑过复制原始的StringBuilder变量并简单地删除字符,但我根本不知道最好的方法。

我不确定我是否应该坚持使用两个循环和一个数组,或者我是否应该只使用一个巨大的if / then条件来检查值。说实话,这似乎是最简单的方法,但似乎也有点过于冗长和低效。

如果有人能帮助我阐明我的愚蠢,我会很感激。这让我疯了。

5 个答案:

答案 0 :(得分:2)

这是备用版本,

String regex = "[aeiou]";
Matcher m = Pattern.compile(regex,Pattern.CASE_INSENSITIVE).matcher(defParagraph); 
while (m.find()) {
  vowelCount++;
}
String vowParagraph=defParagraph.replaceAll(regex, "").toLowerCase();  

答案 1 :(得分:1)

您可以像这样更改循环以避免倍数:

for (int i = 0; i < sbParagraph.length(); i++) {
    char c = defParagraph.toLowerCase().charAt(i);
    boolean isVowel = false;
    for (int j = 0; j < vowels.length; j++) {
        if (c == vowels[j]) {
            isVowel = true;
            break;
        }
    }
    if (isVowel) {
        vowelCount++;
    } else {
        vowParagraph.append(c);
    }
}

答案 2 :(得分:1)

您还没有说明您的结果应该是什么?你只想计算句子中有多少个元音?或者你想在最后代表一个代表独特元音的字符串?

如果你想要一个包含句子中所有元音的结尾的字符串,那么就按照你的想法去做。在for(int j...循环中附加元音。你看到倍数的原因是因为句子中有倍数。 (2个,2个,5个)。

编辑:我刚刚注意到您的问题声明“需要帮助将consonants附加到StringBuilder”。你为什么甚至关心元音?

编辑2:要将辅音仅附加到Stringbuilder,请尝试使用

    String defParagraph = "This is an example sentence.";
    StringBuilder sbParagraph = new StringBuilder(defParagraph);
    StringBuilder conPara = new StringBuilder();

    System.out.println("Characters: " + sbParagraph.length());

    for (int i = 0; i < sbParagraph.length(); i++) {
        char c = sbParagraph.toString().toLowerCase().charAt(i);
        if (c == 'a' || c=='e' || c=='i' || c=='o' || c=='u') {
            continue; // Skip this character.
        }
        conPara.append(c);
    }

    System.out.println("conPara: " + conPara);

输出是:

 Characters: 28
 conPara: ths s n xmpl sntnc.

由于这是作业,我会留给你弄清楚如何删除空格。 (它们既不是元音也不是辅音)。

答案 3 :(得分:1)

如何避免O(N^2)循环?

Set<Character> vowels = new HashSet<Character>(Arrays.asList('a','e','i','o','u'));  
int vowelCount = 0;
String sbParagraph = "This is an example sentence.";
StringBuilder vowParagraph = new StringBuilder();

System.out.print("Characters: " + sbParagraph.length());

for (int i = 0, len = sbParagraph.length(); i < len; i++) {  
    int theChar = sbParagraph.charAt(i);
    if(vowels.contains(Character.toLowerCase(theChar)){    
        vowelCount++;    
     }  
     else{  
         vowParagraph.append(theChar);
      }  
}  

答案 4 :(得分:1)

这类似于其他一些答案,但对您的代码所做的更改进行了一些调整和解释。但请注意,如果正则表达式适合您,请查看Adi的答案。他给你另一种解决问题的方法,但由于这是家庭作业,不确定它是否是一个可行的解决方案。无论如何,有解释(跳到最终产品的底部):

对您声明以

开头的内容的更改
int vowelCount = 0;
// All the Strings/StringBuilders can be final since we will never reinstantiate them
final String defParagraph = "This is an example sentence.";
// We'll just make a lowercase version here. That way we don't 
// .toLowerCase() everytime though the loop, and for people that complain
// about trying to optimize - I think it's easier to read too.
final String lowerCaseVersion = defParagraph.toLowerCase();
// Declare the stringBuilder with the size of defParagraph. That is the
// maximum size the vowel-less text could be, and ensures the stringBuilder
// won't overflow it's initial capacity and have to waste time growing.
final StringBuilder newParagraph = new StringBuilder(defParagraph.length());
// Not using the vowel array. We will remove the loop 
// and just || them together - see below
//char[] vowels = {'a', 'e', 'i', 'o', 'u'};
// You didn't need sbParagraph for anything you had (defParagraph works fine).
// Also, you could have just been a regular String since you never changed it.
//StringBuilder sbParagraph = new StringBuilder(defParagraph);
// Don't need vowParagraph since we aren't tracking the actual vowels, just the count
//StringBuilder vowParagraph = new StringBuilder("");

对实际循环的更改

 for (int i = 0; i < lowerCaseVersion.length(); i++) {
  // grab the current character
  char tempChar = lowerCaseVersion.charAt(i);
  if ('a' == tempChar || 'e' == tempChar || 'i' == tempChar 
        || 'o' == tempChar || 'u' == tempChar) {
    // It matched one of the vowels, so count it
    vowelCount ++;
  } else {
    // It didn't match a vowel, so add it the consonants stringBuilder
    // Oh, and append a character from the original, not the lowerCaseVersion
    newParagraph.append(defParagraph.charAt(i));
  }
}

然后一起没有评论:

int vowelCount = 0;
final String defParagraph = "This is an example sentence.";
final String lowerCaseVersion = defParagraph.toLowerCase();
final StringBuilder newParagraph = new StringBuilder(defParagraph.length());

System.out.println("Characters: " + defParagraph.length());

for (int i = 0; i < lowerCaseVersion.length(); i++) {
  char tempChar = lowerCaseVersion.charAt(i);
  if ('a' == tempChar || 'e' == tempChar || 'i' == tempChar 
        || 'o' == tempChar || 'u' == tempChar) {
    vowelCount ++;
  } else {
    newParagraph.append(defParagraph.charAt(i));
  }
}

System.out.println("\tVowel: " + vowelCount);
System.out.println("\tDefPara: " + defParagraph.toString());
System.out.println("\tNewPara: " + newParagraph.toString());

输出如下:

Characters: 28
  Vowels: 9
  DefPara: This is an example sentence.
  NewPara: Ths s n xmpl sntnc.

备注

  1. 在这种情况下,使用final实际上是可选的。我倾向于尽我所能地使用它,但这可能是个人偏好。 This Question对何时使用final进行了一些讨论,可能值得一试。