我有一个名为“ line”的字符串,其中包含一个单词。该单词每次都是随机的,我希望有一个循环,可以用星号替换随机单词中的每个字母。到目前为止,我有一个可以用星号替换字母e的循环。有没有一种方法可以修改此循环,以使所有字母都被替换,而不是仅用剩余的25个字母复制并粘贴此循环25次?还有大写字母吗?
非常感谢。
for (w = 0; w <= strlen(line); w++)
{
if (line[w] == 'e')
{
line[w] = '*';
}
}
答案 0 :(得分:0)
该程序会将"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.
答案 1 :(得分:0)
简单地逐个字符地遍历字符串:
void to_asterisks ( char *line ) {
while ( *line != '\0' ) {
*line++ = '*';
}
}
之所以有效,是因为所有基本字符串都以NUL终止,line
指针递增直到达到NUL(零,上面显示为char'\ 0')。该功能可替换字符。