一.编写字符串函数的意义
1.借此学习文字处理的方法;
2.C库函数功能,不能满足所有要求;
3.你可以成为开发系统函数的人;
二.字符串复制(下标法)
#include <stdio.h>
char* scopy(char* str1, const char* str2);
int main()
{
char s1[50];
scopy(s1, "I am happy.");
printf("%s\n", s1);
return 0;
}
char* scopy(char* str1, const char* str2)
{
int i = 0, j = 0;
while (str1[i++] = str2[j++]);
/技巧: 赋值运算,'\0'的ASCII码值为0时为假,退出循环
return str1;
}
运行结果:
I am happy.
关键代码的3种写法
第一种写法:代码简洁
{
int i = 0, j = 0;
while (str1[i++] = str2[j++]);
}
指针法表示:
{
char* p1 = str1; const char* p2 = str2;
while (*p1++ = *p2++);
}
第二种写法:常用写法
{
int i = 0, j = 0;
while (str2[j] != '\0')
str1[i++] = str2[j++];
str1[i] = '\0';
}
指针法表示:
{
char* p1 = str1;
const char* p2 = str2;
while (*p2) //注意:更简洁
*p1++ = *p2++;
*p1 = '\0';
}
第三种写法:便于理解
{
int i = 0, j = 0;
while (str2[j] != '\0')
{
str1[i] = str2[j];
++i;
++j;
}
str1[i] = '\0';
}
指针法表示:
{
char* p1 = str1;
const char* p2 = str2;
while (*p2) //注意:更简洁
{
*p1 = *p2;
p1++;
p2++;
}
*p1 = '\0';
}
二.比较字符串,忽略大小写
实例: 比较验证码是否输入正确
方法一: 指针法
#include <stdio.h>
#include <ctype.h> //使用tolower()函数用
int scomp(const char* str1, const char* str2);
int main()
{
printf("%d\n", scomp("PFXa", "pfXA"));
printf("%d\n", scomp("PF12", "pF34"));
printf("%d\n", scomp("Bxb3", "bdef"));
return 0;
}
int scomp(const char* str1, const char* str2)
{
const char* p = str1, * q = str2;
while (tolower(*p) == tolower(*q) && *p != '\0' && *q != '\0')
{
p++;
q++;
}
if (tolower(*p) > tolower(*q))
return 1;
else if (tolower(*p) < tolower(*q))
return -1;
else
return 0;
}
方法二: 下标法
#include <stdio.h>
//#include <ctype.h> 取消头文件,不用库函数比较
int scomp(const char* str1, const char* str2);
int main()
{
printf("%d\n", scomp("PFXa", "pfXA"));
printf("%d\n", scomp("PF12", "pF34"));
printf("%d\n", scomp("Bxb3", "bdef"));
return 0;
}
int scomp(const char* str1, const char* str2)
{
int i = 0;
char c1, c2;
do
{
c1 = (str1[i] >= 'A' && str1[i] <= 'Z') ? str1[i] + 32 : str1[i];
c2 = (str2[i] >= 'A' && str2[i] <= 'Z') ? str2[i] + 32 : str2[i];
i++;
} while (c1 == c2 && c1 != '\0' && c2 != '\0');
if (c1 > c2)
return 1;
else if (c1 < c2)
return -1;
else
return 0;
}
三.统计单词个数
#include <stdio.h>
int wordnum(const char* str);
int main()
{
char s[81];
gets(s);
printf("\"%s\"have %d words.\n", s, wordnum(s));
return 0;
}
int wordnum(const char* str)
{
int i, num = 0, word = 0;
for (i = 0; *(str + i) != '\0'; i++)
{
if (*(str + i) == ' ')
word = 0; //遇到空格,word值为0
else if (word == 0) //遇到不是空格,且word=0;
{
word = 1; //word值为1,表示读到字符;
num++; //前面是空格,现又遇到字符,那么就找到一个单词,单词数量加1;
}
}
return num;
}
运行结果:
We are on road.
" We are on road."have 4 words.
代码分析: 其中word代表一种状态
word==0时(之前读到了空格)
①现遇到空格,word保持0
②现遇到非空格,单词数增1,word置为1
word==1时(之前读到的是非空格)
①现读到空格,word重置为0
②现读到了非空格,继续读