2016-04-15 6 views
0

文字列は、n個の等しい部分文字列で構成されています。たとえば、文字列"hellooo dddd"には3つの部分文字列(3回発生したと言います)が3つあります("dd")。より一般的なケースでは、文字列に等しいn個の部分文字列がある場合、文字列中のi番目の文字列をどのように置き換えることができますか。 A、i番目の部分文字列の場合はreplace()のようになります。私はそれを私のアンドロイドコードで実装したいと思います。 (英語は私の母国語ではないので、間違いをお許しください)。文字列中のi番目の出現箇所を置換する最速の方法

+3

String.indexOf(value、fromIndex)を繰り返し使用します。 – ControlAltDel

答えて

1
public static String replace(String input, String pattern, int occurence, String replacement){ 
    String result = input; 
    Pattern p = Pattern.compile(pattern); 
    Matcher m = p.matcher(result); 
    if(occurence == 0){ 
     return result; 
    } else if(occurence == 1){ 
     m.find(); 
     result = result.substring(0,m.start()) + replacement + result.substring(m.end()); 
    } else { 
     m.find(); 
     int counter = 1; 
     try { 
      while((counter<occurence)&&m.find(m.start()+1)){ 
       counter++; 
      } 
      result = result.substring(0,m.start()) + replacement + result.substring(m.end()); 
     } catch(IllegalStateException ise){ 
      throw new IllegalArgumentException("There are not this many occurences of the pattern in the String."); 
     } 
    } 
    return result; 
} 

私が正しく理解している場合、似たようなことをしているようです。

マッチャー/パターンシステムを使用すると、はるかに複雑な正規表現が使用できます。

関連する問題