標籤:
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 test(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--) { if(0==test(*(strStr+i),*(strStr+j))) return 0; } return 1;}int main(){ char a[10]="heooeh"; printf("%s\n",isPalindrome(a)?"is Palindrome":"is not Palindrome"); return 0;}
C語言字串操作函數實現