【问题标题】:How to remove the last characters in each word of a string in C? [closed]如何删除 C 中字符串的每个单词的最后一个字符? [关闭]
【发布时间】:2023-01-30 21:24:54
【问题描述】:

例子:输入 -“伦敦是英国的首都”, 输出 -“大不列颠的首都伦敦”. 我是新手,我将不胜感激。

我尝试用 string[strlen(string)-i++] = '\0' 做点什么,但它只对文本的第一个词有效。

【问题讨论】:

  • 欢迎来到 SO。不要描述你的代码,而是展示它。在您的问题中将其添加为格式化文本。
  • 是的......一般来说,删除一个字符意味着将所有内容都从上移到下一个(包括 NUL)。你的教授/助教可能希望你用递归做一些聪明的事情:(

标签: arrays c string sorting


【解决方案1】:

好吧,一个快速而肮脏的答案:

#include <stdio.h>
#include <string.h>

int main()
{
    char *exampletext = "testtextt";
    char *destination = malloc(sizeof(char)  * strlen(exampletext));  

    
    strncpy(destination, exampletext, (strlen(exampletext) -1 ));


    printf("%s", destination);
    free(destination);
    destination = NULL;

    return 0;
}

但对于以后的问题,我建议您详细说明您的问题。

  1. 应该如何收集文本(用户输入或固定文本)?
  2. 将代码块格式化为代码示例

    有关更多信息,请阅读: https://stackoverflow.com/help/how-to-ask

【讨论】:

  • 这有点太快和脏了,我会说......你不会 nul-terminate 切碎的字符串,导致未定义的行为。而问题标题的“in each word of a string”部分根本没有处理。
  • 好吧,对于一个模糊的问题,我的回答应该被解释为可以开始使用的东西。通过为他的问题提供许多可能的解决方案之一,他可以开始深入了解我选择此实现的原因。
猜你喜欢
  • 2021-12-14
  • 1970-01-01
  • 2017-05-01
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 2023-02-03
  • 2015-06-08
  • 1970-01-01
相关资源
最近更新 更多