关于c++字符串的问题

第一段代码不知道为什么会出现segmentation fault,我感觉我写的也没有什么问题吧,是a.size()用的不对吗?后来我把第二个for循环的条件循环条件给改了,不知道为什么又出现了一些莫名其妙的错误?

img

img

img


#include 
#include 
#include 
#include 

using namespace std;

int main(){
    int n;
    cin >> n;
    int count[60];    //小写字母a的ascii值为65,大写字母Z的ascii值为122,122-65=57,所以数组最大为57,开60完全没有毛病啊
    while(n--){
        string a;
        getline(cin,a);
        for(int i=0;isize()-1;i++){
            count[a[i]-'a']++;
        }
            int max=count[0],x=0;
        for(int i=0;i<60;i++){
            if(count[i]=='\0') break;
            if(count[i]>max) 
                 x=i;
                max=count[i];
        }
           
            cout << " " << max;
    }
}

#include 
#include 
#include 
#include 

using namespace std;

int main(){
    int n;
    cin >> n;
    int count[60];    //小写字母a的ascii值为65,大写字母Z的ascii值为122,122-65=57,所以数组最大为57,开60完全没有毛病啊
    while(n--){
        string a;
        getline(cin,a);
        for(int i=0;isize()-1;i++){
            count[a[i]-'a']++;
        }
            int max=count[0],x=0;
        for(int i=0,strlen(count);iif(count[i]=='\0') break;
            if(count[i]>max) 
                 x=i;
                max=count[i];
        }
           
            cout << " " << max;
    }
}

题目并没说只输入小写字符吧,如果是大写字符或者其他字符的话,会导致数组越界异常。

我把 那个int count[60]写进了循环里面并给他改成了 int count[60]={0},还是相同的错误

你的count是int性不能用strlen来计算长度

img

会不会是把’\0’也算进去了,循环里a.size()-2试试呢

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632

你的算法也有问题,要找最长连续出现的字符,不是统计字符串中哪个字符出现次数最多。

#include <iostream>
#include <string>

std::pair<char, int> find_longest_continuous_character(const std::string &str) {
  std::pair<char, int> result{};
  auto itr = str.begin();
  while (itr != str.end()) {
    auto from = itr;
    auto ch = *itr;
    do {
      ++itr;
    } while (*itr == ch && itr != str.end());
    auto count = std::distance(from, itr);
    if (count > result.second) {
      result.first = ch;
      result.second = count;
    }
  }
  return result;
}

int main() {
  int n;
  std::string str;
  std::cin >> n;
  for (int i = 0; i < n; i++) {
    std::cin >> str;
    auto result = find_longest_continuous_character(str);
    std::cout << result.first << ' ' << result.second << '\n';
  }
  return 0;
}