[英]How to count consecutive times a character appears in a String
我有代碼
public static int count(String text, char letter)
{
int amount = 0;
for(int i = 0; i < text.length(); i++)
{
if(text.charAt(i) == letter)
amount++;
}
return amount;
}
計算某個字母在字符串中出現的次數(例如: eeeeee
有 6 個e
)。
但是我將如何 go 關於返回一個字符連續出現的次數只有一個字符串參數?
例如:
AAbcde
將返回1
(第一個a
之后的一個a
)abcde
將返回0
(無連續計數)abccd
將返回1
(第一個c
之后的一個c
)aabccc
將返回3
(第一個a
之后的一個a
+ 兩個c
的第一個c
之后)有沒有什么簡單的方法可以實現類似於我已經擁有的代碼?
您可以嘗試下一個代碼
public static int count(String text)
{
int amount = 0;
for(int i = 1; i < text.length(); i++)
{
if(text.charAt(i) == text.charAt(i-1))
amount++;
}
return amount;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.