【问题标题】:Display short form of a string显示字符串的短格式
【发布时间】:2020-05-08 16:50:49
【问题描述】:

我是 C 编程的初学者。我最近尝试解决一个简单的问题来查找字符串的短形式。我不明白为什么我们在程序中使用*(ptr+i-1)。如果我只使用* (ptr+i) 会怎样。谁能告诉我这是如何工作的?

#include<stdio.h>
#include<string.h>
int main()
{
    char sent[100];
    char *ptr;
    printf("Enter a sentence : ");
    gets(sent);

    char len=strlen(sent);
    printf("%c",*sent);
    ptr=&sent;
    for(int i=1; i<len; i++)
    {
        if(*(ptr+i-1) == ' ')
        {
            printf(" %c",*(ptr+i));
        }
    }
    return 0;
}

【问题讨论】:

  • 您正在寻找索引前一个字符的空格字符。标记一个新单词的开始。
  • ".. 如果我只使用* (ptr+i) .." - 这真是太好了,你可以继续尝试。
  • here复制的整个同上代码。
  • *(ptr+i-1) 的特点是初学者如何编写经验丰富的 C 程序员所写的 ptr[i-1]。同样*(ptr+i) 只是ptr[i]

标签: c string short


【解决方案1】:

我不明白为什么我们在程序中使用*(ptr+i-1)。如果我只使用* (ptr+i) 会怎样。谁能告诉我这是如何工作的?

for(int i=1; i<len; i++)
{
    if(*(ptr+i-1) == ' ')
    {
        printf(" %c",*(ptr+i));
    }
}

*(ptr+i-1) 很重要,因为i 开始/初始化为1 而不是0 关于从第一个字符而不是第二个字符读取字符串。

使用*(ptr+i),您将改为从字符串的第二个字符读取。


旁注:

gets(sent); -> 不要使用gets(),它已被弃用:

Why is the gets function so dangerous that it should not be used?

【讨论】:

  • 如果我启动了i=0,会是什么情况?
  • @Code_Ostrich 那么就可以了。
  • 我尝试使用 0 但我没有得到输出。只显示第一个字符。
  • @Code_Ostrich 你想得到什么作为输出?一个字符串?然后改用%s
  • 不,我尝试了与 i=0 相同的编辑,并且 if 条件为 if(*(ptr+i) == ' ') { printf(" %c",*(ptr+i)) ; }
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 2022-01-20
  • 2013-01-29
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
相关资源
最近更新 更多