c 语言字符串查找替换,c ++ - 如何在标准字符串中搜索/查找和替换?

c ++ - 如何在标准字符串中搜索/查找和替换?

有没有办法用std::string中的另一个字符串替换所有出现的子字符串?

例如:

void SomeFunction(std::string& str)

{

str = str.replace("hello", "world"); //< I'm looking for something nice like this

}

Adam Tegen asked 2019-09-09T00:24:14Z

10个解决方案

148 votes

#include // include Boost, a C++ library

...

std::string target("Would you like a foo of chocolate. Two foos of chocolate?");

boost::replace_all(target, "foo", "bar");

这是关于replace_all的官方文档。

TheNamelessOne answered 2019-09-09T00:24:48Z

70 votes

为什么不实施自己的替换?

void myReplace(std::string& str,

const std::string& oldStr,

const std::string& newStr)

{

std::string::size_type pos = 0u;

while((pos = str.find(oldStr, pos)) != std::string::npos){

str.replace(pos, oldStr.length(), newStr);

pos += newStr.length();

}

}

yves Baumes answered 2019-09-09T00:24:24Z

25 votes

在C ++ 11中,您可以通过调用regex_replace作为单行程序执行此操作:

#include

#include

using std::string;

string do_replace( string const & in, string const & from, string const & to )

{

return std::regex_replace( in, std::regex(from), to );

}

string test = "Remove all spaces";

std::cout << do_replace(test, " ", "") << std::endl;

输出:

Removeallspaces

nobar answered 2019-09-09T00:25:13Z

15 votes

为什么不返回修改后的字符串?

std::string ReplaceString(std::string subject, const std::string& search,

const std::string& replace) {

size_t pos = 0;

while((pos = subject.find(search, pos)) != std::string::npos) {

subject.replace(pos, search.length(), replace);

pos += replace.length();

}

return subject;

}

如果您需要性能,这里是一个修改输入字符串的优化函数,它不会创建字符串的副本:

void ReplaceStringInPlace(std::string& subject, const std::string& search,

const std::string& replace) {

size_t pos = 0;

while((pos = subject.find(search, pos)) != std::string::npos) {

subject.replace(pos, search.length(), replace);

pos += replace.length();

}

}

测试:

std::string input = "abc abc def";

std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: "

<< ReplaceString(input, "bc", "!!") << std::endl;

std::cout << "ReplaceString() input string not changed: "

<< input << std::endl;

ReplaceStringInPlace(input, "bc", "??");

std::cout << "ReplaceStringInPlace() input string modified: "

<< input << std::endl;

输出:

Input string: abc abc def

ReplaceString() return value: a!! a!! def

ReplaceString() input string not modified: abc abc def

ReplaceStringInPlace() input string modified: a?? a?? def

Czarek Tomczak answered 2019-09-09T00:25:51Z

6 votes

我的模板化内联就地查找和替换:

template

int inline findAndReplace(T& source, const T& find, const T& replace)

{

int num=0;

typename T::size_t fLen = find.size();

typename T::size_t rLen = replace.size();

for (T::size_t pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)

{

num++;

source.replace(pos, fLen, replace);

}

return num;

}

它返回替换项目数的计数(如果要连续运行,则使用,等等)。 要使用它:

std::string str = "one two three";

int n = findAndReplace(str, "one", "1");

Marius answered 2019-09-09T00:26:21Z

3 votes

最简单的方法(提供你写的东西附近)是使用Boost.Regex,特别是regex_replace。

std :: string内置了find()和replace()方法,但由于它们需要处理索引和字符串长度,所以它们使用起来比较麻烦。

Alan answered 2019-09-09T00:26:52Z

3 votes

我相信这会奏效。它将const char *作为参数。

//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;

}

}

Adam Tegen answered 2019-09-09T00:27:16Z

2 votes

#include

#include

#include

#include

#include

using namespace boost::algorithm;

using namespace std;

using namespace boost;

void highlighter(string terms, string text) {

char_separator sep(" ");

tokenizer > tokens(terms, sep);

BOOST_FOREACH(string term, tokens) {

boost::replace_all(text, term, "" + term + "");

}

cout << text << endl;

}

int main(int argc, char **argv)

{

cout << "Search term highlighter" << endl;

string text("I love boost library, and this is a test of boost library!");

highlighter("love boost", text);

}

我喜欢boost库,这是对boost库的测试!

Kevin Duraj answered 2019-09-09T00:27:40Z

1 votes

// Replace all occurrences of searchStr in str with replacer

// Each match is replaced only once to prevent an infinite loop

// The algorithm iterates once over the input and only concatenates

// to the output, so it should be reasonably efficient

std::string replace(const std::string& str, const std::string& searchStr,

const std::string& replacer)

{

// Prevent an infinite loop if the input is empty

if (searchStr == "") {

return str;

}

std::string result = "";

size_t pos = 0;

size_t pos2 = str.find(searchStr, pos);

while (pos2 != std::string::npos) {

result += str.substr(pos, pos2-pos) + replacer;

pos = pos2 + searchStr.length();

pos2 = str.find(searchStr, pos);

}

result += str.substr(pos, str.length()-pos);

return result;

}

Björn Ganster answered 2019-09-09T00:27:58Z

0 votes

#include

using std::string;

void myReplace(string& str,

const string& oldStr,

const string& newStr) {

if (oldStr.empty()) {

return;

}

for (size_t pos = 0; (pos = str.find(oldStr, pos)) != string::npos;) {

str.replace(pos, oldStr.length(), newStr);

pos += newStr.length();

}

}

检查oldStr是否为空是很重要的。 如果由于某种原因该参数为空,您将陷入无限循环。

但是如果可以的话,是的,请使用久经考验的C ++ 11或Boost解决方案。

ericcurtin answered 2019-09-09T00:28:28Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用C语言的文件操作函数和字符串处理函数来实现替换文件的字符和字符串。 首先,使用fopen函数打开要操作的文件,并指定打开方式为“读写”或“只写”。然后,使用fgets函数逐行读取文件内容,对每行内容进行字符串处理,查找需要替换的字符或字符串,使用strcpy和strcat函数将替换后的字符串写入到一个新的文件。最后,使用fclose函数关闭文件。 以下是一个简单的示例代码,用于替换文件的字符: ```c #include <stdio.h> #include <string.h> int main() { FILE *fp1, *fp2; char c, old_char, new_char; char filename[100]; // 输入文件名和需要替换的字符 printf("Enter the filename: "); scanf("%s", filename); printf("Enter the character to replace: "); scanf(" %c", &old_char); printf("Enter the new character: "); scanf(" %c", &new_char); // 打开文件 fp1 = fopen(filename, "r"); fp2 = fopen("temp.txt", "w"); // 逐个字符读取文件内容,替换需要替换的字符并写入到新文件 while ((c = fgetc(fp1)) != EOF) { if (c == old_char) { fputc(new_char, fp2); } else { fputc(c, fp2); } } // 关闭文件 fclose(fp1); fclose(fp2); // 删除原文件并将新文件重命名为原文件名 remove(filename); rename("temp.txt", filename); printf("Replacement completed!\n"); return 0; } ``` 如果需要替换字符串,可以使用strstr函数查找需要替换字符串,并使用strcpy和strcat函数将替换后的字符串写入到新的文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值