知识点总结:
1.字符函数
2.字符串函数
3.编写自己的字符串函数
a).字符串复制
while(str1[i++]=str2[j++]); //当str2[10]='\0',则str1[10]='\0',退出循环
b).统计单词个数
int wordnum(const char *str){
int i,num=0,word=0; //word从0变为1时计数,word初始化为0
for(i=0; (*(str+i)!='\0'); i++){
//只有当出现第一个字符是字母,以及前一个是空格后一个是字母是计数
if (*(str+i)==' ')
word=0;
else if (word==0){
word=1; //表示扫描到了字母
num++; //新词数+1
}
}
return num;
}
c).去除句子中所有多余的空格,返回去除了空格的字符串
#include <stdio.h>
void palltrim(char str[]);
int main(void){
char s[81]=" Some spaces before the first word. ";
printf("请输入一个句子:");
printf("原句子:\"%s\"\n", s);
palltrim(s);
printf("去除多余空格后为:\"%s\"\n", s);
return 0;
}
void palltrim(char *str){
char *p=str,*q=str;
int notSpace=0;
while(*q==' ')
q++;
while(*q!='\0'){
if (*q!=' '){ //扫描到不是空格的字符
notSpace=1;
*p++=*q++; //复制非空格字符
}
else if (notSpace){ //扫描到空格,但前一个不是空格
notSpace=0;
*p++=*q++; //复制空格
}
else{ //扫描到空格,但前一个是空格
q++;
}
}
*p='\0';
}