我正在用 c 语言学习字符串,并且正在做我的家庭作业,要求我编写一个程序来在某些情况下替换部分字符串。这是我的源代码(未完成):
#include <stdio.h>
#include <string.h>
int main()
{
char str1[128], str2[128], str3[128];
for (int i = 0; i < 128; i++) //initialize str
{
str1[i] = 0;
str2[i] = 0;
str3[i] = 0;
}
printf("Input the first string:"); //inputs
fgets(str1, 128, stdin);
printf("Input the second string:");
fgets(str2, 128, stdin);
printf("Input the third string:");
fgets(str3, 128, stdin);
if (strncmp(str1, str2, strlen(str2) - 1) == 0) //if the first n charters match (n=length of str2)
{
printf("%s", str3); //print str3
int RemainingChar = 0;
RemainingChar = strlen(str1) - strlen(str2);
for (int i = 0; i < RemainingChar; i++)
{
printf("%c", str1[i + strlen(str2) - 1]); //print the remaining part
}
}
return 0;
}
这是它的运行方式:
Input the first string:asdfghjkl
Input the second string:asd
Input the third string:qwe
qwe
fghjkl
出现意外的换行符。我应该怎么做才能让它像这样输出:qwefghjkl
?
最佳答案
函数fgets
还将行尾的换行符 '\n'
存储到字符串中。如果您不想打印此换行符,则必须在打印字符串之前将其删除。
有关删除换行符的几种方法,请参见以下问题:
关于c - c中printf中的意外换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69990745/