字串的倒序 字串轉數字 數字轉字串 獲取最長的單詞
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
字串的倒序“abcd”->“dcba”
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--;
}
}
//“123a45”->123,“a123”->0
int Myatoi(const char *str)//todo 負數,正號,最大值,前面的空格
{
int sum = 0;
while(isdigit(str))
{
sum = sum
str++;
}
return sum;
}
char *Myitoa(int n)//error
{
char str[100];
return str;
}
//12345->“54321”->“12345”
//todo 負數
void Myitoa(char *str,int n)//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)//bug 尾部有問題
{
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 main()
{
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;
}