题:
首先笔者的第一思路是前后两个字符串比较。如果相同index++。
#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
int main()
{string s;cout << "6请输入字符串:" << endl;cin >> s;string name = "";unsigned int iSize = s.size();int currVal = 0;for (int i = 0; i <iSize; i++){int j = i;if (s[j] == s[j+1])currVal++;elsecurrVal = 0;}cout << currVal << endl;switch (currVal){case 0:name = "a Foolish Man"; break;case 1:name = "a Foolish Man"; break;case 2:name = "a Foolish Man"; break;case 3:name = "a Foolish Man"; break;case 4:name = "Dominating"; break;case 5:name = "a Mega-Kill"; break;case 6:name = "Unstoppable"; break;case 7:name = "Wicked Sick"; break;case 8:name = "a M-m-m-m...Monster Kill"; break;case 9:name = "Godlike"; break;default:name = "Beyond Godlike";break;}std::cout << name;system("pause");return 0;
}
当我输入题示要求后ok。但是当输入DDDKKKK是期待输出是4但是输出为0.
分析结果是因为在j和j+1比较时j+1会出界。所以最后会置为0
后来网上搜索字符串中字符连续个数:
#include"string"
#include"iostream"
using namespace std;
int main()
{string str;cin>>str;int lenght=str.length();int index=0;int i;int j;for(i=0;i<length;i=j){index=1;for(j=i+1;j<length;++j){if(str[i]==str[j])index++;else break;}cout<<str[i]<<index;}cout<<endl;system("pause");return 0;
}
这个程序在数连续字符时完全没有问题。它采用起始为1,然后和后续比较,若不相同直接从不相同处开始比较的思想。但是如果最后是一个D或者多个D时我需要输出为0.为一个K时输出为1.。。试了多次依然没有成功
最后。突然用自己之前一个错误s[+1]起始就一直是s[0]的错误解决,就是每个字符都和K进行比较
#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
int main()
{string s ;cout << "3请输入字符串:" << endl;cin >> s;string name="";unsigned int iSize = s.size();int currVal = 0;for (int i = 0; i <iSize; i++){if (s[i]=='K')currVal++;elsecurrVal = 0;}cout << currVal << endl;switch (currVal){case 0:name = "a Foolish Man"; break;case 1:name = "a Foolish Man"; break;case 2:name = "a Foolish Man"; break;case 3:name = "a Foolish Man"; break;case 4:name = "Dominating"; break;case 5:name = "a Mega-Kill"; break;case 6:name = "Unstoppable"; break;case 7:name = "Wicked Sick"; break;case 8:name = "a M-m-m-m...Monster Kill"; break;case 9:name = "Godlike"; break;default:name = "Beyond Godlike";break;}std::cout<<name;system("pause");return 0;
}
此时满足题意。
参考自https://blog.csdn.net/qq_27302361/article/details/51111537