字符串操作
我真不明白优快云的代码编辑器怎么这么垃圾,我写代码写了1小时,把代码弄上来要2小时,真不想说什么
1 内存内容交换
int swap( void *first, void *second, size_t size)
{
void *tmp;
tmp = malloc(size);
memcpy(tmp,first,size);
memcpy(first,second,size);
memcpy(second,tmp,size);
free(tmp);
return 0;
}
int swap (void *p, void *q, size_t size)
{
int i;
char t;
for (i = 0; i < size; i++)//用内存来交换
{
t = *((char *)p + i);
*((char *)p + i) = *((char *)q + i);
*((char *)q + i) = t;
}
}
2 字符串逆序如"hello world" ---> "world hello"
void reverse(char* str,int len)
{
int i = 0,j = len - 1;
char temp;
while(j > i)
{
temp = *(str+i);
*(str + i) = *(str + j);
*(str + j) = temp;
i++, j--;
}
}
char* strReverse(char *str)
{
int len;
reverse(str,strlen(str));//整体进行逆序转换
while(*str != '\0')
{
len = 0;
while( isalnum( *str ) )//找到连续的单词
str++,len++;
if(len > 0)
reverse(str,len);
if(*str == '\0')
break;
str++;
}
return str;
}
3
char *replace(char *str,char *oldstr,char *newstr)
{
char *st = str;
int i,a,b;
oldlen = strlen(oldstr);
newlen = strlen(newstr);
while((s = strstr(st,oldstr)) != NULL)
{
memmove(s + newlen, s + oldlen, strlen(s + oldlen) + 1);
memmove(s,newstr,newlen);
st += newstr;
}
return str;
}
5 大数相乘 "124567888" * "29348573"基本思想是把对应位的数相乘放到对应位,因为数组的一个位能表示0 ~ ((unsigned int) -1 >> 1),然后通过求余进位
char* multiply(char* x,char* y,char* z)
{
int a[n],b[n],c[2 * n],i = 0,j = 0,alen = 0,blen = 0,clen = 0;
alen = strlen(x) - 1;
blen = strlen(y) - 1;
for(i = 0;i < alen;i++)
*(a + i) = *(x + alen - i - 1) - '0';
for(i = 0;i < blen;i++)
*(b + i) = *(y + blen - i - 1) - '0';
for(i = 0;i < alen;i++)
for(j = 0;j < blen;j++)
*(c + i + j) += *(a + i) * *(b + j);
for(i = 0;i <= alen + blen ;i++)
{
*(c + i + 1) += *(c + i) / 10;
*(c + i) = *(c + i) % 10;
}
clen = alen + blen;
if(*(c + alen + blen - 1) == 0)
clen--;
for(i = 0;i < clen;i++)
*(z + clen - i - 1) = *(c + i) + '0';
*(z + clen) = '\0';
return z;
}
to be continue.....