字符串中的字符替换 [英] Replacing character in a string

查看:109
本文介绍了字符串中的字符替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  什么是用C来替换字符串函数?

我想在我的字符串与多个字符替换某个字符。这里是什么,我试图做一个例子。

I am trying to replace a certain character in my string with multiple characters. Here is an example of what I am trying to do.

说我有字符串aaabaa

Say I have the string "aaabaa"

我想替换字母b5CS的所有地方。

I want to replace all occurrences of the character "b" with 5 "c"s.

所以,当我完成后,aaabaa变成aaacccccaa

So when I am done, "aaabaa" becomes "aaacccccaa"

我写了下面的code:

I have written the following code:

#include <stdio.h>
#include <string.h>
int main(void)
{
    char s[20] = "aaabaa";
    int i, j;
    for (i=0; s[i]!= '\0'; i++)
    {
        if (s[i] == 'b')
        {
            for (j=0; j<5; j++)
            {
                s[i+j] = 'c';
            }
        }
    }
    printf("%s\n", s);
}

从这个功能我的输出是aaaccccc。看来,它只是将覆盖上两个A与C的。有没有什么办法,我要这样,最后的夫妇的的不被覆盖?

My output from this function is "aaaccccc". It appears that it just overwrites the last two a's with the c's. Is there any way I would have it so that these last couple of a's dont get overwritten?

推荐答案

您的问题是,你代替CCCCC到原始字符串从而覆盖其余的字符你的愿望后,更换...你应该复制到新的字符串,并保持两个指数跟踪 - 各有一个

Your problem is that you replace the "ccccc" into the original string thus overwriting the remaining characters after what you wish to replace... You should copy into a new string and keep track of two indices - one in each.

和高兴的是,你声明个char [20] 比你原来的字符串的大小加上替换值,否则你已经创建了一个缓冲区溢出漏洞在关键的登录系统的脆弱性: - )

And be happy that you declared char s[20] larger than the size of your original string plus the replace values, as otherwise you'd have created a buffer overflow vulnerability in your critical login system :-)

干杯,

这篇关于字符串中的字符替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆