2012-04-11 3 views
0

너무 많은 후에 혼수 상태 (,)를 삭제해야합니다. 거기에 4 개의 혼수 상태의 "i, am, ok, today, hello"라는 문자열이 있다고합시다. 2 회 이후에 재설정을 삭제하고 싶지만 처음 2 번 이후에 혼자만 삭제하면됩니다.Android : 너무 많은 문자를 삭제하는 방법?

답변

0

이와 같이해야합니다.

public string StripCommas(string str, int allowableCommas) { 
    int comma; 
    int found = 0; 
    comma = str.indexOf(","); 
    while (comma >= 0) { 
     found++; 
     if (found == allowableCommas) { 
      return str.substring(0, comma) + str.substring(comma + 1).replaceAll(",", "");    
     } 
     comma = str.indexOf(",", comma + 1); 
    } 
    return str; 
} 
0

yourString.split(",")를 사용하여 문자열 배열로 문자열을 분할이 개 당신이 할 수있는 방법,

  1. 를 사용하여 분할 문자열이 있습니다.
  2. 문자열 배열을 반복하고 처음 2 개 요소 뒤에 ","를 추가하고 나머지는 추가하십시오.

B

  1. 것은 같이 IndexOf를 사용하여 두 번째 콤마의 위치 찾기()
  2. 이 시점에서 문자열을 분할.
  3. 두 번째 하위 문자열에서 ","를 ""로 바꾸고 첫 번째 하위 문자열에 추가하십시오. 문자열을 통해
1

루프, 재건의 StringBuilder를 사용하여 쉼표 확인 :

static String stripCommasAfterN(String s, int n) 
{ 
    StringBuilder builder = new StringBuilder(s.length()); 
    int commas = 0; 

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

     if (c == ',') 
     { 
      if (commas < n) 
      { 
       builder.append(c); 
      } 
      commas++; 
     } 
     else 
     { 
      builder.append(c); 
     } 
    } 

    return builder.toString(); 
} 
관련 문제