字符串的常见用法
*1、字符串:用""包括的字符序列,末尾自带’\0’。只要以’\0’结尾的字符序列都是字符串(只要遇到’\0’就认为字符串已经结束)
2、0:’\0’,false,NULL
3、重要的等式:str[i] == (str+i)
//字符串的复制
//desstr = srcstr(将左值赋值给右值)
void Mystrcpy1(char *desstr,char *srcstr)
{
int i;
for(i=0;srcstr[i]!='\0';i++)
{
desstr[i] = srcstr[i];
}
desstr[i] = '\0';
}
//用指针的形式实现
void Mystrcpy2(char *desstr,char srcstr)
{
int i;
for(i=0;(srcstr+i)!=’\0’;i++)
{
*(desstr+i) = *(srcstr+i);
}
*(desstr+i) = ‘\0’;
}
void Mystrcpy(char *desstr,char *srcstr)
{
while(*srcstr != '\0')
{
*desstr = *srcstr;
desstr++;
srcstr++;
}
*desstr = '\0';
}
//字符串连接:des = des+src
//“abc”+“xyz”->“abcxyz”
void Mystrcat(char *des,char *src)
{
while(*des!='\0')
{
des++;
}
while(*src != '\0')
{
*des = *src;
des++;
src++;
}
*des = '\0';
}
//求字符串的长度(有效字符个数不包含’\0’)
int Mystrlen(char *str)
{
int count = 0;
while(*str != '\0')
{
count++;
str++;
}
return count;
}
//strlen(str);求字符串str的有效长度,不包含\0
//sizeof(a);求a的字节数
int main()
{
char str1[100] = "abcde";
char str2[] = "abcde";
char str3[100] = "abcdef\n\0ghi";
char str4[] = "abcdef\n\0ghi";//数组不管\0
char *str5 = "abcde";
char *str6 = "abcdef\n\0ghi";
printf("%d,%d\n",strlen(str1),sizeof(str1));//5,100*1
printf("%d,%d\n",strlen(str2),sizeof(str2));//5,6*1
printf("%d,%d\n",strlen(str3),sizeof(str3));//7,100
printf("%d,%d\n",strlen(str4),sizeof(str4));//7,12
printf("%d,%d\n",strlen(str5),sizeof(str5));//5,4
printf("%d,%d\n",strlen(str6),sizeof(str6));//7,4
return 0;
}
//统计单词的个数:字母遇上非字母则为一个单词
#include “ctype.h"
int Words(const char *str)
{
int count = 0;
while(*str != '\0')
{
if(isalpha(*str) && !isalpha(*(str+1)))
//isalpha(*str)检测一个整数是否为字母;
//isalpha(*(str+1))当前为字母下一个为非字母
{
count++;
}
str++;//继续往后走
}
return count;
}
int main()
{
char *str = " adf45adf 567tyum,adf";
printf("%d\n",Words(str));
return 0;
}