C++中統計具有相同相鄰字元的字元個數


給定一個字串,例如str,任務是計算字串str中具有相同相鄰字元的字元個數,這包括字元左右兩側的字元。在這種情況下,字串的第一個和最後一個字元始終被考慮在內,因為它們只有一個相鄰字元。

例如

Input − string str = “poiot”
Output − count is 3

說明 − 在給定的字串中,字元p、t和i具有相同的相鄰字元,因此計數將增加到3。

Input − string str = “nitihig”
Output − count is 4

說明 − 在給定的字串中,字元n、t、h和g具有相同的相鄰字元,因此計數將增加到4。

下面程式中使用的演算法如下

  • 將字串輸入到變數中,例如str

  • 使用length()函式計算字串str的長度,該函式將根據字串中字母的數量(包括空格)返回一個整數值。

  • 如果字串的長度小於或等於2,則返回字串長度作為計數,因為所有字元都將被計算。

  • 如果字串長度大於2,則將計數初始化為2。

  • 現在,從i=1開始迴圈,直到i小於(length-1)

  • 在迴圈內,檢查如果(str[i-1] = str[i+1]),則計數增加1

  • 現在返回計數的總值

  • 列印結果。

示例

 線上演示

#include <iostream>
using namespace std;
// To count the characters
int countChar(string st){
   int size = st.length();
   if (size <= 2){
      return size;
   }
   int result = 2;
   // Traverse the string
   for (int i = 1; i < size - 1; i++){
      // Increment the count by 1 if the previous
      // and next character is same
      if (st[i - 1] == st[i + 1]){
         result++;
      }
   }
   // Return result
   return result;
}
int main(){
   string st = "poiot";
   cout <<"count is " <<countChar(st);
   return 0;
}

輸出

如果執行上述程式碼,它將生成以下輸出

count is 3

更新於:2020年5月15日

193 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.