简体   繁体   English

用C ++替换字符串中的字符

[英]Replacing characters in a string in C++

In my application, I will be retrieving error message strings from a database. 在我的应用程序中,我将从数据库中检索错误消息字符串。 I would like to substitute numbers into the error message. 我想将数字替换为错误消息。 The error message will be a C style string like: 错误消息将是C样式字符串,如:

Message %d does not exist

or 要么

Error reading from bus %d

Ideally, I would like to be able to do a C style printf using this statement, and substituting my own numbers in. I know I can just do it manually, but is there an easier way to somehow use it like a string in a regular printf? 理想情况下,我希望能够使用这个语句做一个C风格的printf,并用我自己的数字代替。我知道我可以手动完成它,但有一种更简单的方法可以像常规中的字符串一样使用它printf的?

Apart for simple string concatenation or using << together with number and a message. 除了简单的字符串连接或使用<<与数字和消息一起使用。

I can think of boost::format 我可以想到boost::format

int message_no=5;
std::cout << boost::format("Message %d doesn't exist") % message_no ;

The C++ way is to use std::stringstream: C ++的方法是使用std :: stringstream:

std::stringstream str;
str << "Message " << messageName << " doesn't exist";

std::string out = str.str();

There is also very nice header-only boost string algorithms library : 还有非常好的仅限标题的提升字符串算法库

std::string message = "Message %s doesn't exist";
boost::replace_first( str, "%s", "MyMessage" );

// message == "Message MyMessage doesn't exist"

and boost::format , which acts like printf, but is entirely type-safe and supports all user-defined types: boost::format ,其作用类似于printf,但完全是类型安全的,并支持所有用户定义的类型:

std::string out = format( "Message %1 doesn't exist" ) % "MyMessage";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM