字串逆序、轉數字、獲取最長單詞
阿新 • • 發佈:2018-12-22
主要內容:針對於字串的基本操作:字串逆序、獲取最長單詞、數字字元轉數字、數字轉字串、十六進位制字串轉十進位制數
//字串逆置 void Reverse_str(char *str) { char *p; for(p=str;*p!='\0';p++) ; char tmp; p--; while(str < p)//str != p { tmp = *str; *str = *p; *p = tmp; str++; p--; } } //字串轉數字 int Myatoi(const char *str)//"123a45"->123,"a123"->0 { int sum = 0; while(isdigit(*str)) { sum = sum*10 + (*str-'0'); str++; } return sum; } char *Myitoa(int n)//error { char str[100]; return str; } //數字轉字串 void Myitoa(char *str,int n)//12345->"54321"->"12345" { int i = 0; do { str[i++] = n%10 + '0'; n /= 10; }while(n != 0); str[i] = '\0'; Reverse_str(str); } //獲取最長的單詞,記憶體有函式建立,使用完後請注意釋放記憶體 char *MaxWord(const char *str) { int len = strlen(str); char *str1 = (char *)malloc((len+1)*sizeof(char));//存放當前單詞 char *str2 = (char *)malloc((len+1)*sizeof(char));//存放最長單詞 int cur = 0; // 當前單詞的長度 int max = 0;//最長單詞的長度 while(*str != '\0') { if(isalpha(*str)) { str1[cur++] = *str; } else { if(cur > max) { str1[cur] = '\0'; strcpy(str2,str1);//將當前單詞拷貝到最長單詞 } cur = 0; } str++; } //bug free(str1); return str2; } //十六進位制字串轉十進位制數 int HexToi(const char *str) //"0x1b"->27,"0x123"->291 { int tmp = 0; if(str[0]!='0' || str[1]!='x'&&str[1]!='X') { return 0; } str += 2; while(isxdigit(*str)) { if(isdigit(*str)) { tmp = tmp*16 + (*str-'0'); } else // 字母,大寫,小寫 { tmp = tmp*16 + (tolower(*str)-'a'+10); } str++; } return tmp; } int main() { int a = HexToi("0x1234"); int b = HexToi("0X12ab"); int c = HexToi("0x12AB"); int d = HexToi("12ab"); int e = HexToi("0x12gh"); printf("%d,%x\n",a,a); printf("%d,%x\n",b,b); printf("%d,%x\n",c,c); printf("%d,%x\n",d,d); printf("%d,%x\n",e,e); //char *p = MaxWord("asdf ad ewrt ,adffad,awqwerrt"); //printf("%s\n",p); //free(p); //char str[20]; //Myitoa(str,123456789); //Myitoa(str,0); //printf("%s\n",str); //printf("%d\n",atoi("1234567")); //printf("%d\n",atoi("1234a567")); //printf("%d\n",atoi(" 1234")); //printf("%d\n",atoi("a1234567")); //printf("%d\n",atoi("1234567890987654321")); //printf("%d\n",atoi("-1234567"));// /*char str1[] = "abcd"; Reverse_str(str1); printf("%s\n",str1);*/ return 0; }