替换 c 中给定字符串的字符串的空格

To replace the whitespaces of string given string in c

我想用字符串 "IIT" 替换空格。我尝试在我的字符串中使用循环,当我遇到空格时,我尝试用给定的字符串替换它。但是空格类似于字符串中的单个字符,因此它不会替换为单词所以请帮助我如何用给定的 word.Thank you .

替换我的空格

C String manipulation Standard Library APIs are not that strong to simply replace a Strings. So, You can use lexical analyzer utilities like Flex which give a REGEX power to find and manipulate 你的短信。

Here is a program which compresses multiple blanks and tabs down to a single blank, and throws away whitespace found at the end of a line:

%%
[ \t]+        putchar( ' ' );
[ \t]+$       /* ignore this token */

Flex 将为您生成一个 C 程序,它会完成所有工作。

教程: http://alumni.cs.ucr.edu/~lgao/teaching/flex.html

你不能,因为你说你想用 "IIT" 替换空格。这里 "IIT" 有 3 个字节,空白是一个字节。那你怎么能存储它。您可以通过在放置字符串 "IIT" 之前分配更多内存来做到这一点。有关详细信息,请参阅 realloc

在不使用第二个字符串的情况下用多个字符替换字符串中的单个字符的技巧是从头到尾处理字符串。

首先,遍历一次字符串,计算要替换的字符数。然后计算您的替换将添加多少个额外字符。确保字符串有足够的 space 分配来处理新字符。然后从字符串中的最后一个字符开始,将每个字符移动到字符串的新末尾,用您的替换字符替换特定字符。

例如,将 x 替换为 zz

xcfdxdfxg---

(破折号是为字符串分配的space,但目前没有使用,当然字符串末尾应该有一个[=14=],它也被正确地移动了)

xcfdxdfxg---
xcfdxdfx---g
xcfdxdf--zzg
xcfdxd--fzzg
xcfdx--dfzzg
xcfd-zzdfzzg
xcf-dzzdfzzg
xc-fdzzdfzzg
x-cfdzzdfzzg
zzcfdzzdfzzg