转换中的字符串错误

时间:2013-11-22 21:23:02

标签: java string char

所以我的代码适用于某些单词而不是其他单词,它会冲出字符串索引超出范围:-1 我想在每个元音和元音簇之前打印出ub 前可疑将是dubububious或cat loveo将是lubovudeo

String sentance,set;

        sentance = "toster iooppp";
        set= translate(sentance);
        System.out.println(set);
}
public static String translate (String sentence){

    String set = " ";
    sentence= sentence.toLowerCase();
    scan = new Scanner (sentence);

    while (scan.hasNext()) {

        set+= toUbbi (scan.next());
        set += " "; 
    }
    return  set; 
    }

 private static String toUbbi(String word ) {
    String str= word;
    String new_str="";
     for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (isVowel(c) && isVowel(str.charAt(i -1)) )
            { // If is a vowel
                new_str += "ub" ;
            }
            new_str += c;
        }
     return new_str;
    }


    private static boolean isVowel(char c)
    {
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ){
            return true;}

        return false;    

1 个答案:

答案 0 :(得分:0)

在第一次迭代中它给出错误..

        if (isVowel(c) && isVowel(str.charAt(i -1)) )
        { // If is a vowel
            new_str += "ub" ;
        }

所以这样改变..

        if (isVowel(c))
        { // If is a vowel
            new_str += "ub" ;
        }

或改变你的循环..

  for (int i = 1; i < str.length(); i++) {
      // yur remain code...
  }