(1)求字符串长度。
(2)实现strcmp函数。
(3)在一个字符串中找到可能的最长的子字符串,该子字符串是由同一字符组成的。
代码1(自己写的):
#include <iostream>
#include <cstring>
#include <stdio.h>
const int maxn = 100;
using namespace std;
//(1)求字符串长度。int mylength(char *str)
int mylength(char *str)
{
int add = 0;
while(str[add] != '\0')
{
add++;
}
return add;
}
/*
int main()
{
int x;
char w[100];
gets(w);
x = mylength(w);
printf("string number is %d",x);
return 0;
}
*/
/*
//(2)实现strcmp函数。int mystrcmp(char* str1, char* str2)
int mystrcmp(char *str1,char *str2)
{
while(*str1 != '\0' && *str2 != '\0')
{
if(*str1 == *str2)
{
str1++;
str2++;
}
else if(*str1 > *str2)
{
return 1;
}
else if(*str1 < *str2)
{
return -1;
}
}
if(*str1 == '\0' && *str2 == '\0')
return 0;
if(*str1 == '\0' && *str2 != '\0')
return -1;
if(*str1 != '\0' && *str2 == '\0')
return 1;
}
int main()
{
char a[maxn],b[maxn];
gets(a);
gets(b);
printf("%d\n",mystrcmp(a,b));
}
*/
//(3) 在一个字符串中找到可能的最长的子字符串,该子字符串是由同一字符组成的。int myChildString(char *p)
int myChildString(char *p)
{
int cot = 1,i = 1;
int most = 1; //保存最大长度
while(i <= mylength(p))
{
while((i <= mylength(p)) && (p[i] == p[i-1]))
{
cot++;
i++;
}
if(cot > most)
{
most = cot;
cot = 1;
}
i++;
}
return most;
}
int main()
{
//scanf("%s",num);
char num[maxn]="aabbb";
printf("the most length is %d",myChildString(num));
}
代码2(西交无尽):
int mylength(char *str){
char *q = str;
int length = 0;
while(*q != '\0'){
length++;
q++;
}
return length;
}
int myStrcmp(char *str1,char *str2){
if(str1 == NULL || str2 == NULL){
return -2;
}
//循环去除相同字符
//str1 = "aaaa" str2 = "aabb"
while(*str2 == *str1 && *str2 != '\0' && *str1 != '\0'){
str1++;
str2++;
}
if(*str1 == *str2) return 0;
else if(*str1 > *str2) return 1;
else return -1;
}
int myChildString(char *p){
char *str = p;
int L = mylength(str);
int Stringlen = 1,maxlen = 1,i = 0;
while(*(str+i) != '\0'){
if(*(str+i) == *(str+i+1) && (i+1 < L)){
Stringlen++;
}
else {
if(Stringlen > maxlen) maxlen = Stringlen;
Stringlen = 1;
}
i++;
}
return maxlen;
}
(感谢西交无尽学长提供以上题目练习)