怎么替换字符串中的空格君?

怎么把字符串的里的空格君都给替换了呢?我之前没用C语言写过,今天尝试了下,小编太笨了,写写改改,到这会儿终于弄好了。

先谈谈思路,既然要将空格替换,我就要现将空格标示出来,此处借助的是字符数组的下标i来实现。用一个中间字符串变量tmp来表示替换的结果,给tmp分配适当的空间。当一开始有空格的时候就要先将要替换的字符串接入,有几个空格就重复strcat几次一直到开始的空格全部被替换,然后将原字符串从首个非空格处接入tmp。i向后移动直到下一个空格处(标示tmp的下标要同步往后移动)再次执行上一步操作直到循环不满足条件。



<span style="font-size: 24px; font-family: Arial, Helvetica, sans-serif;">//替换字符串中的所有空格为%20</span>
<span style="font-size: 24px;">#include<stdio.h>
#include<string.h>
#include<malloc.h>

void replace(char *str,char *ss)//str原字符串,ss是要替换的字符串
{
        int i = 0;
	int j = -1;   //j下标从-1开始,因为数组从0 开始计数
	int n1 = strlen(str);
	int n2 = strlen(ss);
	char *tmp = (char*)malloc(sizeof(char) * n1 * 2);
        // 为tmp分配合适的空间
	while(i < n1 && str[i] == ' ')//循环替换开头的所有空格
	{
		tmp = strcat(tmp,ss);
		i++;
		j+=n2;
	}
	tmp = strcat(tmp,&(str[i]));//从首个非空字符接入
       
	while(i < n1 )
	{
		if(str[i] == ' ')
		{
		   tmp[j+1] = '\0';//在空格处接入ss
	           while(i < n1 && str[i] == ' ')
                   {
		       tmp = strcat(tmp,ss);
		       i++;
		       j+= n2;
	           }
			tmp = strcat(tmp,&(str[i]));			
		}
               else
		{
			i ++;
			j ++;
		}
	}
	printf("%s\n",tmp);
}

int main()
{
	char *str = "     hello sandy nice to meet to you";
	char *ss ="%20";
	printf("替换之前str = %s\n",str);
	printf("替换之后str = ");
        replace(str,ss);

	return 0;
}</span>

运行结果:
替换之前str =      hello sandy nice to meet to you
替换之后str = %20%20%20%20%20hello%20sandy%20nice%20to%20meet%20to%20you

程序写的有些复杂,先记下,以后水平提高的时候再重整,(*^__^*) 嘻嘻……

<span style="font-size: 24px; font-family: Arial, Helvetica, sans-serif;">//替换字符串中的所有空格为%20</span>
<span style="font-size: 24px;">#include<stdio.h>
#include<string.h>
#include<malloc.h>

void replace(char *str,char *ss)
{
    int i = 0;
	int j = -1;
	int n1 = strlen(str);
	int n2 = strlen(ss);
	char *tmp = (char*)malloc(sizeof(char) * n1 * 2);

	while(i < n1 && str[i] == ' ')
	{
		tmp = strcat(tmp,ss);
		i++;
		j+=n2;
	}
	tmp = strcat(tmp,&(str[i]));

	while(i < n1 )
	{
		if(str[i] == ' ')
		{
		   tmp[j+1] = '\0';
	       while(i < n1 && str[i] == ' ')
           {
		       tmp = strcat(tmp,ss);
		       i++;
		       j+= n2;
	       }
			tmp = strcat(tmp,&(str[i]));			
		}
        else
		{
			i ++;
			j ++;
		}
	}
	printf("%s\n",tmp);
}

int main()
{
	char *str = "     hello sandy nice to meet to you";
	char *ss ="%20";
	printf("替换之前str = %s\n",str);
	printf("替换之后str = ");
    replace(str,ss);

	return 0;
}
</span>

你可能感兴趣的:(怎么替换字符串中的空格君?)