我一直在试图弄清楚如何循环遍历 char 数组,例如
char line[50] = "this is a string";
每次都加一个空格
line[counter] == ' ';
因此,所有空格的字符串都是原来的两倍。
最佳答案
首先你应该统计空白字符的个数,然后向后复制字符串。
例如
#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;
}
程序输出为
this is a string
this is a string
更有效的方法如下
#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;
}
关于c - 如何在c中将多个字符插入到char数组的中间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42157831/