gpt4 book ai didi

c - 使用指针从字符串中删除空格

转载 作者:行者123 更新时间:2023-12-04 11:36:16 26 4
gpt4 key购买 nike

#include<stdio.h>

int main()
{
unsigned int n=0;
char str[100];
char *ptr,*ptr1;
printf("Enter the string = ");
gets(str);
ptr = &str[0];
while(*ptr!='\0')
{
n++;ptr++;
}
ptr=&str[0];
while(*ptr!='\0')
{
if(*ptr==' ')
{
n--;
for(ptr1=++ptr;*ptr1!='\0';ptr1++)
{
*ptr=*ptr1;
ptr++;
}
ptr=&str[0];
}
ptr++;
}
printf("Modified string = ");
for(int i=0;i<n;i++)
{
printf("%c",str[i]);
}
return 0;
}

我知道从字符串中删除空格的另一种方法,但我想使用指针来执行此操作,但我无法理解这段代码有什么问题?

我真的很感激一些小小的帮助。

最佳答案

iharob 确定了您的问题并提供了一个很好的解决方案,但我想向您展示一种略有不同的方法。

char *rd; // "read" pointer
char *wr; // "write" pointer

rd = wr = string; // initially, both read and write pointers point to
// beginning of the string

while ( *rd != 0 ) // while not at end of string
{
while ( isspace( *rd ) ) // while rd points to a whitespace character
rd++; // advance rd
*wr++ = *rd++; // copy *rd to *wr, advance both pointers
}
*wr = 0; // terminate the result

printf( "squished: %s\n", string );

通过测试字符串 "This is a test",我们开始如下(\0 代表字符串终止符):

+----------------------- rd
|
V
This is a test\0
^
|
+----------------------- wr

前四个字符不是空格,所以我们只是用相同的值覆盖这些字符并推进两个指针,给我们

    +------------------- rd
|
V
This is a test\0
^
|
+------------------- wr

因为 rd 指向空白,我们继续前进直到找到一个非空白字符:

        +--------------- rd
|
V
This is a test\0
^
|
+------------------- wr

然后我们将该非空白字符写入wr 指向的位置:

        +--------------- rd
|
V
Thisi is a test\0
^
|
+------------------- wr

一直这样直到我们找到下一个空白字符:

          +------------- rd
|
V
Thisis is a test\0
^
|
+----------------- wr

继续rd前进到下一个非空白字符:

           +------------ rd
|
V
Thisis is a test\0
^
|
+----------------- wr

将其写入wr:

           +------------ rd
|
V
Thisisa is a test\0
^
|
+----------------- wr

起泡、冲洗、重复:

                   +---- rd
|
V
Thisisatesta test\0
^
|
+------------ wr

rd 现在指向字符串的末尾。我们退出主循环并向wr写入一个0来终止字符串:

                   +---- rd
|
V
Thisisatest\0 test\0
^
|
+------------ wr

我更喜欢这个解决方案,因为每个角色只移动一次到它的最终位置。您最终会覆盖字符串开头不需要的字符,但我认为这是一个合理的权衡。

编辑

Chux 的版本有点圆滑,而且绝对更符合 C 的精神:

do
{
while ( isspace( *rd ) ) // while rd points to whitespace
rd++; // advance rd
}
while ( (*wr++ = *rd++) ); // copy rd to wr, advance pointers until
// we see the string terminator

同样,每个角色只会移动一次到其最终位置。

关于c - 使用指针从字符串中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31036058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com