[英]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;
}
有兩種方法可以做,
一種
yourString.split(",")
。乙
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.