簡體   English   中英

如何計算字符在字符串中出現的連續次數

[英]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.

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