统计字符串中每个连续字符个数

题目:统计字符串中每个连续字符个数;

输入:随机给出字符串,如aaabbcccaab;

输出:统计连续且相同字符串的个数并输出,如3a2b3c2a1b;

/*1. js实现*/
function char_count(str) {
  var res = " ";
  var cnt = 1;
  var ch = str[0];
  for(var i = 1; i < str.length; i++){
    if(ch == str[i])
      cnt++;
    else{
      res += cnt;
      res += ch;
      cnt = 1;
      ch = str[i];
     }
  }

  res += cnt;
  res += ch;
  return res;
}

/*输入输出*/
var res;
var _str = read_line();
res = char_count(_str);
print(res);

 

/*2.c++实现*/

#include <oistream>

#include <vector>

#include <numeric>

#include <limits>

using namespace std;

string char_count(string str){

  string str;

  int cnt = 1;

  char ch = str[0];

  for(int i=1;i<str.length();i++){

    if(ch == str[i]){

      cnt++;

    }else{

      res = res + char(cnt + '0');

      res = res + ch;

      cnt = 1;

      ch = str[i];

    }

  }

  res = res + char(cnt + '0');

  res = res + ch;

  return res;   

}

int main(){

  string res;

  string  _str;

  getline(cin , _str);

  res = char_count(_str);

  cout << res << endl;

  return 0;

}

posted @ 2018-10-15 13:26  T-Leo-D  阅读(2569)  评论(0编辑  收藏  举报