简体   繁体   English

c - 如何在c中的char数组的中间插入多个字符?

[英]How to insert multiple chars to the middle of a char array in c?

I'm stuck trying to figure out how I can loop through a char array such as我一直试图弄清楚如何循环遍历字符数组,例如

char line[50] = "this is a string";

and add an extra space every time并每次都添加一个额外的空间

line[counter] == ' ';

Thus resulting in the string with all the spaces being twice as long.因此导致所有空格的字符串都是两倍长。

At first you should count the number of blank characters and then copy backward the string.首先,您应该计算空白字符的数量,然后向后复制字符串。

For example例如

#include <stdio.h>

int main(void) 
{
    char s[50] = "this is a string";

    puts( s );

    size_t n = 0;
    char *p = s;

    do
    {
        if ( *p == ' ' ) ++n;
    } while ( *p++ );

    if ( n != 0 )
    {
        char *q = p + n;

        while ( p != s )
        {
            if ( *--p == ' ' ) *--q = ' ';
            *--q = *p;
        }
    }

    puts( s );

    return 0;
}

The program output is程序输出是

this is a string
this  is  a  string

A more efficient approach is the following更有效的方法如下

#include <stdio.h>

int main(void) 
{
    char s[50] = "this is a string";

    puts( s );

    size_t n = 0;
    char *p = s;

    do
    {
        if ( *p == ' ' ) ++n;
    } while ( *p++ );

    for ( char *q = p + n; q != p; )
    {
        if ( *--p == ' ' ) *--q = ' ';
        *--q = *p;
    }

    puts( s );

    return 0;
}

Here is a solution using another string:这是使用另一个字符串的解决方案:

#include <stdio.h>

int main(void) {
  char line[50] = "this is a string";
  char newline[100]; //the new string, i chose [100], because there might be a string of 50 spaces
  char *pline = line;
  char *pnewline = newline;
  while (*pline != NULL) { //goes through every element of the string
    *pnewline = *pline; //copies the string
    if (*pline == ' ') {
      *(++pnewline) = ' '; //adds a space
    }
    pline++;
    pnewline++;
  }
  printf("%s", line);
  printf("%s", newline);
  return 0;
}

If you wouldn't wan't to use up memory, you could do all this with dynamic memory allocation and free() the "temporary" string.如果您不想用完内存,您可以使用动态内存分配和free() “临时”字符串来完成所有这些。 I didn't do that now, as you used an array aswell.我现在没有这样做,因为您也使用了数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM