/**************************************************************** 找出字符串的最长子串,要求子串的所有字符相同 例如:str ="sssddddabcdef" 则输出字串为:dddd *****************************************************************/ #include<cstdlib> #include<cstdio> #include<cstring> void GetSubstring(char* strSource,char *strSubstring) { int nLen; //源字符串长度 int nCurPos; //当前统计字符串的头指针位置(相对于原字符串第一个字符的位置) int nCurCount; //当前统计字符串的长度(有相同字符组成的子字符串) int nPos; //当前最长的子串的头指针位置 int nCount; //当前最长的子串的长度 nLen = strlen(strSource); //初始化变量 nCount = 1; nPos = 0; nCurCount = 1; nCurPos = 0; //遍历整个字符串 for(int i = 1; i < nLen; i++) { if(strSource[i] == strSource[nCurPos])//如果当前字符与子串的字符相同,子串长度增1 nCurCount++; else //如果不相同,开始统计新的子串 { if(nCurCount > nCount)//如果当前子串比原先最长的子串长,把当前子串信息(起始位置 + 长度)保留下来 { nCount = nCurCount; nPos = nCurPos; } //长度复值为1,新串的开始位置为i nCurCount = 1; nCurPos = i; } } /*****************复制子串(用其他函数也可以)********* for(i = 0; i < nCount; i++) strSubstring[i] = strSource[nPos + i]; strSubstring[nCount] = '\0'; ******************************************************/ strncpy(strSubstring,strSource+nPos,nCount); //注意 strcnpy 危险之处在于不能自动处理字符串结束标志 strSubstring[nCount]='\0'; } int main() { //输入一个字符串strSource char *strSource="sssddddabcdef"; char *output=new char[strlen(strSource)+1]; GetSubstring(strSource,output); printf("最长子串为:%s\n长度为:%d",output,strlen(output)); delete []output; }