-6
如何解析用户给出的字符串,并用新字符串交换旧子字符串的所有匹配项。我有一个可以使用的功能,但是当涉及到字符串时我很不确定。解析字符串和交换子字符串
void spliceSwap(char* inputStr, const char* oldStr, const char* newStr )
如何解析用户给出的字符串,并用新字符串交换旧子字符串的所有匹配项。我有一个可以使用的功能,但是当涉及到字符串时我很不确定。解析字符串和交换子字符串
void spliceSwap(char* inputStr, const char* oldStr, const char* newStr )
最简单的解决方法是在这里使用google(First link)。另请注意,在C++中,我们更喜欢std::string
而不是const char *
。不要编写自己的std::string
,使用内置的。你的代码似乎比C++更多C!
// Zammbi's variable names will help answer your question
// params find and replace cannot be NULL
void FindAndReplace(std::string& source, const char* find, const char* replace)
{
// ASSERT(find != NULL);
// ASSERT(replace != NULL);
size_t findLen = strlen(find);
size_t replaceLen = strlen(replace);
size_t pos = 0;
// search for the next occurrence of find within source
while ((pos = source.find(find, pos)) != std::string::npos)
{
// replace the found string with the replacement
source.replace(pos, findLen, replace);
// the next line keeps you from searching your replace string,
// so your could replace "hello" with "hello world"
// and not have it blow chunks.
pos += replaceLen;
}
}
这是一个家庭作业吗? – 0x499602D2
我们可以看到迄今为止尝试过的代码吗? – Borgleader
这是C或C++吗?如果它是C++,则使用'std :: string'。如果是C,则适当标记它。 –