1、字符串反轉 – strRev
void strRev(char *str) { assert(NULL != str);
int length=strlen(str); char *end=str+length-1; while(end > str) { *str=(*str)^(*end); *end=(*str)^(*end); *str=(*str)^(*end); end--; str++; } }
2、字符串復制 – strcpy
char *strcpy(char *strDest, const char *strStr) { assert((NULL != strDest) && (NULL != strStr)); char *Dest=strDest; while((*Dest++)=(*strStr++)) {} return strDest; }
3、字符串拼接 –strcat
char *strcat(char *strDest, const char *strStr) { assert((NULL != strDest) && (NULL != strStr)); int length=strlen(strDest); char *Dest=strDest+length; while((*Dest++)=(*strStr++)) {} return strDest; }
4、字符串比較 –strcmp
int strcmp(const char *strDest, const char *strStr) { assert((NULL != strDest) && (NULL != strStr)); while(0==(*strDest - *strStr) && *strDest ) { strDest++; strStr++; } if(*strDest > *strStr) return 1; else if(*strDest < *strStr) return -1; else return 0; }
5、字符串長度 –strlen
int strlen(const char *strStr) { assert(NULL != strStr); int length = 0; while('\0' != *strStr) { length++; strStr++; } return length; }
6、字符串轉數字 –atoi
int atoi(const char *strStr) { assert(NULL != strStr); int minus = 0; int begin = 0; int sum = 0; while('\0' !=*strStr) { if(0==begin && (isdigit(*strStr) || '+'==*strStr || '-'==*strStr)) { begin = 1; if('-'==*strStr) { minus = 1; strStr++; continue; } } else if(!isdigit(*strStr)) { printf("format is wrong !\n"); exit(1); } if(1==begin) { sum = sum*10 + (*strStr-'0'); } strStr++; } return minus ? (-sum):(sum); }
7、數字轉字符串 –atoi
char *itoa(int num) { int temp,i,j; char array[10]; static char strDest[10]; for(temp = num,i=0; i<10 && temp ;i++) { array[i]=temp%10+'0'; temp/=10; } for(i=i-1,j=0 ; i>=0 && j<10; i--,j++) { strDest[j]=array[i]; } strDest[j]='\0'; return strDest; }
8、計算字符串中元音字符的個數
#include<stdio.h> #include<stdlib.h> #include<assert.h> #include<ctype.h> int isVowel(char letter) { switch(toupper(letter)) { case 'A': case 'E': case 'I': case 'O': case 'U': return 1; default: return 0; } } int countVowel(const char * strStr) { assert(NULL != strStr); int count=0; while('\0' !=*strStr++) { if(isVowel(*strStr)) count++; } return count; } int main() { char a[10]="hwlulr"; printf("%d\n",countVowel(a)); return 0; }
9、判斷一個字符串是否是回文
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<assert.h> #include<ctype.h> int isEqual(char a,char b) { if(a==b) return 1; return 0; } int isPalindrome(const char * strStr) { assert(NULL != strStr); int length=strlen(strStr); int i,j; for(i=0,j=length-1; i<j ; i++,j--) { /*跳過空格和符號*/ while(' '== *(strStr+i) || !isalpha(*(strStr+i))) i++; while(' '== *(strStr+j) || !isalpha(*(strStr+j))) j--; if(0==isEqual(*(strStr+i),*(strStr+j))) return 0; } return 1; } int main() { char a[10]="heo o, e h"; printf("%s\n",isPalindrome(a) ? "is Palindrome" : "is not Palindrome"); return 0; }