C语言 字符串练习
将int类型数据转为字符串
#include <stdio.h>
char* itoa(char* str,int num)
{
int tmp = abs(num),i = 0;
while(tmp)
{
str[i++] = tmp%10+'0';
tmp /= 10;
}
if(num < 0)
str[i++] = '-'
str[i] = '\0'
char* s = str;
char* e = str+i-1;
while(s < e)
{
char t = *s;
*s = *e;
*e = t;
s++,e--;
}
return str;
}
将句子倒序输出
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void reverse(char* s,char* e)
{
while(s > e)
{
char t = *s;
*s = *e;
*e = t;
s++,e--;
}
}
char* sentence_reverse(char* str)
{
size_t len = strlen(str);
reverse(str,str+len-1);
char *s = str,*e = NULL;
for(int i = 1; i <= len; i++)
{
if(!isalpha(str[i]) && '\''!=str[i])
{
e = str+i-1;
reverse(s,e);
}
if(isalpha(str[i])||('\''==str[i])&&(!isalpha(str[i-1])&&'\''!=str[i-1]))
{
s = str + i;
}
}
return str;
}
两个数字字符串相加
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
void resver(char* str)
{
size_t len = strlen(str);
for(int i = 0; i < len/2; i++)
{
char ch = str[i];
str[i] = str[len-i-1];
str[len-i-1] = ch;
}
}
char* str_add(const char* s1,const char* s2,char* ret)
{
const char* t1 = s1+strlen(s1)-1;
const char* t2 = s2+strlen(s2)-1;
const char *sl = NULL,*tl = NULL;
char* tmp = ret;
char carry = 0;
while(true)
{
char s = (*t1-'0')+(*t2-'0')+carry;
*tmp++ = s%10+'0';
carry = s/10;
if(t1==s1)
{
tl = t2;
sl = s2;
break;
}
if(t2 == s2)
{
tl = t1;
sl = s1;
break;
}
t1--,t2--;
}
while(tl != sl)
{
char s = (*tl-'0')+carry;
*tmp = s%10+'0';
carry = s/10;
tl--,tmp++;
}
if(carry)
*tmp++ = carry+'0';
*tmp = '\0';
resver(ret);
return ret;
}
|