C语言学习之字符串:替换空格

  • Post author:
  • Post category:其他




替换空格



函数描述

函数:

char *replace_blank(char *source)

功能:

将字符串中的空格替换为

"%20"

的字符串。

思路:

while(字符串未到末尾\0)
{
	if(此处字符为空格)
	{
		子函数:删除空格符;
		子函数:字符串向后挪动可以插入数组的空间;
		子函数:将目标数组插入到字符数组的前几位;
		字符串向后移位跳过插入的数组;
	}
	如果没有空格符,则再向后移位判断;
}

难点:

涉及到的子函数较多,由于数组插入操作本身就是需要移位再插入,需要基本的子函数进行操作。

涉及

continue

的使用。

缺点:

暂时还没有。

时空复杂度为

O(n)



函数代码

/* 替换空格 */
/** 删除空格符 **/
void delete_array(char *source, int offset)
{
  int i;
  int len = strlen(source);

  for (i = 0; i < len && source[i] != '\0'; i++)
  {
    source[i] = source[i + offset];
  }

}
/** 向后挪动字符数组 **/
void move_array(char *source, int offset)
{
  int i;
  int len = strlen(source);

  for (i = len + offset; i >= 0; i--)
  {
    source[i] = source[i - offset];
  }
}

/* 将字符串赋值到字符数组的前几位 */
void string_set(char *source,char *buf, int offset)
{
  int i;
  for (i = 0; i < offset; i++)
  {
    source[i] = buf[i];
  }
}

char *replace_blank(char *source)
{
  char *temp = source;
  int len = strlen(source);//不计算空字符,如何判断是否为最后一位
  char *replace_buf = (char *)"%20";
  unsigned int replace_len = strlen(replace_buf);
  int i;

  for(i = 0; i < len; i++)
  {
    if (*source == ' ')
    {
      delete_array(source, 1);//删除空格
      move_array(source, replace_len);//向后挪动,以便插入数组
      string_set(source, replace_buf, replace_len);//将数组赋值到前几位
      source += replace_len;
      continue;
    }
    source++;
  }

  return temp;
}```



```cpp
#define MAXLINE 100000
static char source[MAXLINE] = "I am a student.";

void test_replace_blank()
{
  replace_blank(source);
  cout << "The replace result:" << source << endl;
}

int main()
{
  test_replace_blank();
  system("pause");
  return 0;
}
  



测试结果

在这里插入图片描述



版权声明:本文为weixin_42098322原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。