主要内容:针对于字符串的基本操作:字符串逆序、获取最长单词、数字字符转数字、数字转字符串、十六进制字符串转十进制数
//字符串逆置
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;
}