2016-10-11 42 views
1

所以這就是我想要做的。我拿一個給定的字符串,並創建一個新的字符串。新的字符串將與原始字符串相同,但會使輔音翻倍。例如,rabbit變成rrabbitt等等。它只會使尚未加倍的輔音翻倍。檢查一個字符串是否有元音,並創建一個新的字符串,使輔音加倍

這是我到目前爲止有:

// Returns a new string in which all consonants in the given string are doubled. 
// Consonants that are already doubled are not doubled again. 
// For example, doubleConsonants("rabbit") returns "rrabbitt". 
// It is assumed that in the given string is alphabetic and that no character 
// appears more than twice in a row. 
// Parameters: 
// s - given string 
// Returns new string with all consonants doubled 
---------------------------------------------------------------------------- 
public static String doubleConsonants(String s) { 

    String newString = ""; 
    String vowels = "aeiouAEIOU"; 

    for (int i = 0; i < s.length(); i++) { 

     boolean hasVowel = false; 
     for (int n = 0; n == 10; n++){ 

      if (vowels.charAt(n) == s.charAt(i)) { 

       newString += s.charAt(i); 
       i++; 
       hasVowel = true; 
       break; 
      } 
     } 
     if (hasVowel = false && s.charAt(i) != s.charAt(i+1) && s.charAt(i) != s.charAt(i-1)) { 

      newString += s.charAt(i); 
      i++;     
     } 
     else if (hasVowel = false) { 

      newString += s.charAt(i); 
      i++; 
     } 
    } 
    return newString; 
} 

顯然有一些問題與「死代碼」和布爾hasVowels是「不使用」。我在搞什麼?

+0

您的for循環從不起作用。用for(int n = 0; n == 10; n ++)。 for循環只在條件n == 10是真的時才起作用,永遠不會。 – Moonstruck

+0

我以爲n = 0是開始點,n == 10是結束... – Muldawg2020

+0

我該如何改變它,所以它會經歷10次迭代? – Muldawg2020

回答

1

試試這個。

public static String doubleConsonants(String s) { 
    return s.replaceAll("(?i)(([^aeiou])\\2+)|([^aeiou])", "$1$3$3"); 
} 
+0

像是認真的,發生了什麼事,我在哪裏學習? – Muldawg2020

+0

@ Muldawg2020請參閱文檔[String.replaceAll](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceAll-java.lang.String-java.lang.String - )和[Pattern](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern。html) – saka1029

+0

這是瘋了。謝謝你給我看。它仍然是WAAAYY在我的頭上,但我要去了解它:) – Muldawg2020

3

你可以做一件事。使用contains()方法將大大減少您的所有工作。

for (int i = 0; i < s.length(); i++) { // traverse through the string 
    if (i < s.length() - 1 && s.charAt(i) == s.charAt(i + 1)) { 
      newString += s.charAt(i); // handles the double constant special condition like bb in rabbit 
      i++; 
    } else if (vowels.contains("" + s.charAt(i))) { //check if the letter is a vowel 
     newString += s.charAt(i); // if yes, add it once 
    } else { 
     newString += "" + s.charAt(i) +s.charAt(i); // else add it twice 
    } 
} 

在此代碼塊的末尾,您將在newString中存儲所需的字符串。你可以閱讀更多關於contains()

+0

試過了,但它給出了錯誤在你的第二行: '該方法包含(CharSequence)在字符串類型不適用於參數(字符)' 我可以通過使'元音'數組? – Muldawg2020

+0

只需將它轉換爲一個字符串,使它「」+ s.charAt(i) – Moonstruck

+0

不幸的是,由於某種原因不工作...我通讀它,它似乎在概念上工作,但它不表現它應該的方式。就像如果你在'rabbit'上試試它不會返回'rrabbitt' .... – Muldawg2020

1

我注意到的第一件事是,底部的if語句使用賦值運算符。您想使用double-equals來測試該值。我將不得不更加密切關注更多的邏輯。

相關問題