字符串复制
#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(str2[j]!='\0') { str1[i]=str2[j]; i++; j++; } str1[i]='\0'; return str1; }
另解:字符串复制
#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) { char *p1=str1; const char *p2=str2; while(*p2!='\0') { *p1=*p2; p1++; p2++; } *p1='\0'; return p1; }
比较字符串(忽略大小写)
#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) { 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> 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, j=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++; j++; }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; } /* 关键:word代表一种状态 word==0时,之前读到了空格 - 现读到空格,word保持0 - 现读到了非空格,单词数增1,word置为1 word==1时,之前读到的是非空格 - 现读到空格,word重置为0 - 现读到了非空格,继续读 */ int wordnum(const char *str) { int i,num=0,word=0; //word为0,代表现在并不 for(i=0; (*(str+i)!='\0'); i++) { if (*(str+i)==' ') word=0; else if (word==0) { word=1; num++; } } return num; }