簡體   English   中英

Android:那么多字符怎么刪除?

[英]Android: How to delete after so many characters?

我需要在這么多之后刪除 coma(,) 。 假設有一個帶有 4 個逗號的字符串“i, am, ok, today, hello”,我想在 2 個逗號之后刪除重置但只保留文本只是在第一個 2 個之后刪除逗號?

遍歷字符串,使用 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();
}

應該這樣做。

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;
}

有兩種方法可以做,

一種

  1. 使用 split string 將字符串拆分為字符串 arrays 使用yourString.split(",")
  2. 循環遍歷字符串數組並在前 2 個元素之后添加“,”,僅在 append 和 rest 之后添加。

  1. 使用 indexOf() 查找第二個逗號的位置
  2. 在這一點上拆分字符串。
  3. 將第二個 substring 和 append 中的“,”替換為“”,將其替換為第一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM