2016-12-15 7 views
0

Stringの数字を掛けて数字を掛けたい場合はStringに戻してください。 数値が9より大きい場合にどのように連結するのか分かりません。 などを掛けてください。私が唯一の文字と1番号などのためにそれを作ったの下"a2b15""a16b4c1""a11b14c5"文字列内の数字で文字を掛ける

String ="a2b10"変換

String ="aabbbbbbbbbb"に文字列が異なる値を持つことができます。 a1b8a4b7v3

import javafx.util.converter.CharacterStringConverter; 

public class Test { 

public static void main(String[] args) { 
    String txt = "a3b2"; 
    char ch; 

    for (int i = 0; i < txt.length(); i++) { 
     ch = txt.charAt(i); 

     if (((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { 

     } else if (ch >= '0' && ch <= '9') 

     { 

      int count = Character.getNumericValue(ch); 
      for (int j = 0; j < count; j++) { 
       System.out.print(txt.charAt(i - 1)); 

      } 

     } else 
      System.out.println("not a letter"); 

    } 
} 

} 
+1

?あなたのコードは*働いていますか?そうでない場合は、何が起こっていると思われますか、どこが間違っていますか? – Makoto

+0

私のコードは1文字1文字のみ変換できます。私は1文字2数字が必要です – elkostek

答えて

2

public static void main(String[] args) { 
    String txt = "a3b10"; 
    String patt = "([a-z])([0-9]*)"; // ([a-z]) will be the first group and ([0-9]*) will be the second 

    Pattern pattern = Pattern.compile(patt); 
    Matcher matcher = pattern.matcher(txt); 

    while(matcher.find()) { 
     String letter = matcher.group(1); 
     String number = matcher.group(2); 
     int num = Integer.valueOf(number); 
     while (num > 0) { 
      System.out.print(letter); 
      num--; 
     } 
    } 
} 

をあなたのコードは、あなたの質問に関連してどのようOUTPUT

aaabbbbbbbbbb 
+0

シンプルで効率的なコードがあり、本当に問題を解決します。それに対して '+ 1'を返します。 –

0

あなたは数字を探していると、あなたが文字または文字列の末尾を見つけるまでの数字を探し続ける、ものを見つけます。あなたはこのようにそれを行うことができます

0

...それはそれを次のようだ文字と数字を抽出する正規表現とグループマッチングを使用する方が簡単です。この場合

public class Test { 

public static void main(String[] args) { 
    String txt = "a10b10"; 
    char ch; 
    char tempChar = ' '; 
    int temp = -1; 
    for (int i = 0; i < txt.length(); i++) { 
     ch = txt.charAt(i); 

     if (((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { 
      temp = -1; 
      tempChar = ch; 
     } else if (ch >= '0' && ch <= '9') { 

      int count = Character.getNumericValue(ch); 

      if (temp != -1) { 
       count = ((10*temp) - temp); 
      } 

      for (int j = 0; j < count; j++) { 
       //System.out.print(txt.charAt(i - 1)); 
       System.out.print(tempChar); 

      } 
      temp = count; 

     } else { 
      System.out.println("not a letter"); 
     } 

    } 

} 

} 
関連する問題