字符串函数

来源:互联网 发布:重庆医疗程序员招聘 编辑:程序博客网 时间:2024/05/18 22:42

#include<stdio.h>
//字符串长度获取 strlen
int mystrlen(char *a);
//字符串连接    strcat
void mystrcat(char *a,char *b);
//字符串比较    strcmp
int mystrcmp(char *a,char *b);
//字符串查询    strfind(char * a,char * b); 返回字符串b在字符串a的位置
//"helnnlo nnnihao","nni"  6,如果不存在返回-1
int strfind(char *a,char *b);
void main()
{
 char str1[100],str2[100];
 printf("请输入两个字符串");
 scanf("%s,%s",str1,str2);
 printf("%s,%s",str1,str2);
 printf("字符串的长度是%d",mystrlen(str1));
 mystrcat(str1,str2);
 printf("连接后的字符串是%s",str1);
 printf("%d,%d",mystrcmp(str1,str2),strfind(str1,str2));


}
//字符串长度获取 strlen
int mystrlen(char *a)
{
 int count = 0;
 while(*a != '\0')
 {
  count ++;
  a ++;
 }
 return count;
}

//字符串连接    strcat
void mystrcat(char *a,char *b)
{
 while(*a != '\0')
 {
  a ++;
 }
 while(*b != '\0')
 {
  *a = *b;
  a ++;
  b ++;
 }
 *a = '\0';
}
//字符串比较    strcmp
int mystrcmp(char *a,char *b)
//{
//for(int i = 0; * a != '\0';i ++)
// for(int j = 0 ; *b != '\0';j ++)
// {
//  if(*a == *b)
//  {
//   a ++;
//   b ++;
//  }
//  else if(*a > *b)
//  {
//   return 1;
//  }
//  else
//  {
//   return -1;
//  }
// }
//  return 0;
//}

{ //a "wang1\0"
  //b "wang2\0"
    int i=0;
    while (1) {
        //判断a,b中第i个字符是否相等
        if(a[i]==b[i])
        {
           if(a[i]=='\0')
           {
             return 0;//两个字符串相等
            }
          i++;
        }else
        {
          if(a[i]>b[i])
              {return 1;}
          else
              {return -1;}
        }
    }
}

//字符串查询    strfind(char * a,char * b); 返回字符串b在字符串a的位置
//"helnnlo nnnihao","nni"  6,如果不存在返回-1
int strfind(char *a,char *b)
{
 
 for(int i = 0; *a != '\0'; i ++)
  {
   int eq = 0;
   for(int j = 0; *b != '\0';j ++)
   {
    if(*(a + i + j) != *(b + j))
    {
     eq = 1;
     break;
    }
   }
  if(!eq)
  {
   return i;
  }
 }
  return -1;
}

 

原创粉丝点击