const char * Str_Replace(const char * c,const char * sub,const char * s3) [英] const char *Str_Replace(const char *c, const char *sub, const char *s3)

查看:88
本文介绍了const char * Str_Replace(const char * c,const char * sub,const char * s3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我需要一些帮助..


我必须在s1中替换,字符串s2用字符串s3替换。我首先发现s2是否是s1中的子串,但我不知道该怎么办,我迷路了..


例如:s1 ="这是一个很好的死亡的日子,s2 =" die,s3 =付费

=>在执行之后s1将是这是一个支付的好日子


这里是函数的代码:

Hello, I need some help..

I have to replace in s1, the string s2 with the string s3. I first found if s2 was a substring in s1, but i dont know what to do from here, I''m lost..

example: s1 = "It is a good day to die", s2 = "die", s3 = "pay up"
=> after execution s1 will be "it is a good day to pay up"

Here''s the code for the function:

展开 | 选择 | Wrap | 行号

推荐答案

您需要创建输出字符串 - 您不能仅仅改变输入字符串s1。我为什么这么说?第一个原因是s1参数被声明为const char *,这意味着不能更改字符串的内容。第二个原因是输出字符串可能比输入字符串长 - 你不能指望s1的内存分配足够大以容纳更长的字符串。


您是否需要更换第一次出现的s2或所有出现的事件?如果你只需要替换第一次出现,那么你可以快速确定为输出字符串分配多少内存:strlen(s1)+ strlen(s3)+ 1.这实际上比你需要的内存多一点,但是我不知道不用担心。


顺便说一句,你的代码与你的文字不一致。函数参数s1,s2,s3或它们是c,sub,s3?
You need to create the output string -- you can''t merely alter input string s1. Why do I say that? The first reason is that the s1 parameter is declared as a const char *, which means that the content of the string can''t be changed. The second reason is that the output string can be longer than the input string -- you can''t count on the memory allocation for s1 to be big enough to hold the longer string.

Do you need to replace the first occurrence of s2 or all occurrences? If you only need to replace the first occurrence then you can quickly determine how much memory to allocate for the output string: strlen(s1) + strlen(s3) + 1. This is actually a little more memory than you need, but I wouldn''t worry about it.

By the way, your code is not consistent with your text. Are the function arguments s1, s2, s3 or are they c, sub, s3?


参数是c,sub和s3,我必须为每次出现而改变..和我不能使用string.h函数:|
the arguments are c, sub, and s3, and i have to change for every occurrance.. and i must not use string.h functions :|


OK ...我假设c与s1相同,sub与s2相同。


别担心< string.h> ......滚动你自己的strlen版本是微不足道的,只要你给它一个不同的名字。


这个问题的答案是什么,你是否应该替换所有sub / s2实例或仅替换第一个?
OK ... I assume that c is the same as s1, and sub is the same as s2.

Don''t worry about <string.h> ... it is trivial to roll your own version of strlen, as long as you give it a different name.

What''s the answer to the question whether you are supposed to replace all instances of sub/s2 or only the first?


这篇关于const char * Str_Replace(const char * c,const char * sub,const char * s3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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