【问题标题】:Replacing every letter in a string using a loop使用循环替换字符串中的每个字母
【发布时间】:2019-05-31 07:27:25
【问题描述】:

我有一个名为“line”的字符串,其中包含一个单词。这个词每次都是随机的,我想要一个循环,可以用星号替换随机词中的每个字母。到目前为止,我有一个可以用星号替换字母 e 的循环。有没有办法修改这个循环,以便替换所有字母,而不是用剩下的 25 个字母复制和粘贴这个循环 25 次?大写字母呢?

非常感谢。

  for (w = 0; w <= strlen(line); w++)
    {
        if (line[w] == 'e')
        {
            line[w] = '*';
        }
    }

【问题讨论】:

  • 显示line的定义。
  • 跳过检查line[w] == 'e'?目前尚不清楚您的线路是什么样的。或者检查isalpha(line[w]),如果您只想更改字母而不更改其他字符。并将w &lt;= strlen(line) 更改为w &lt; strlen(line)
  • for (w = 0; w &lt; strlen(line); w++)

标签: c string loops replace


【解决方案1】:

此程序会将"word" 替换为"****"

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

int main(void)
{
    char text[] = "This a paragraph of words where a random word should be replaced with * instead of word when word is found multiple times.";
    char find[] = "word ";

    printf("Start:  %s\n", text);

    while(strstr(text, find))
    {
        memset(strstr(text,find), '*', strlen(find)-1);
    }

    printf("Result: %s\n", text);

    return 0;
}

输出

Success #stdin #stdout 0s 9424KB
Start:  This a paragraph of words where a random word should be replaced with * instead of word when word is found multiple times.
Result: This a paragraph of words where a random **** should be replaced with * instead of **** when **** is found multiple times.

【讨论】:

    【解决方案2】:

    简单地逐个字符地循环字符串:

    void to_asterisks ( char *line ) {
        while ( *line != '\0' ) {
            *line++ = '*';
        }
    }
    

    这是可行的,因为所有基本字符串都是 NUL 终止的,line 指针会递增,直到达到 NUL(零,如上所示 char '\0')。该函数就地替换字符。

    【讨论】:

      【解决方案3】:

      嗯,如果你想把所有的字母都改成星号,为什么还要加上这个条件呢?这不是你想要的吗?

      auto c = strlen(line);
      
      for (w = 0; w < c; w++)
      {
              line[w] = '*';
      }
      

      【讨论】:

        猜你喜欢
        • 2016-10-26
        • 2015-11-28
        • 1970-01-01
        • 2022-07-07
        • 1970-01-01
        • 2023-03-23
        • 2017-08-04
        • 2020-11-27
        • 1970-01-01
        相关资源
        最近更新 更多