问题描述
我想创建一个包含嵌入信息的字符串.实现我想要的一种方法(不是唯一的方法)称为字符串插值或变量替换,其中字符串中的占位符将替换为实际值.
I want to create a string with embedded information. One way (not the only way) of achieving what I want is called string interpolation or variable substitution, wherein placeholders in a string are replaced with actual values.
在C语言中,我会这样做:
In C, I would do something like this:
printf("error! value was %d but I expected %d",actualValue,expectedValue)
如果我是用python编程,我会做这样的事情:
whereas if I were programming in python, I would do something like this:
"error! value was {0} but I expected {1}".format(actualValue,expectedValue)
这两个都是字符串插值的例子.
both of these are examples of string interpolation.
如何在C ++中做到这一点?
How can I do this in C++?
重要警告:
- 我知道如果要将这样的消息打印到标准输出(不是字符串插值,而是打印出我想要的字符串类型),则可以使用
std :: cout
:
cout << "error! value was " << actualValue << " but I expected "
<< expectedValue;
我不想打印一个字符串到stdout.我想将 std :: string
作为参数传递给函数(例如,异常对象的构造函数).
I don't want to print a string to stdout. I want to pass a std::string
as an argument to a function (e.g. the constructor of an exception object).
- 我正在使用C ++ 11,但是可移植性可能是一个问题,因此,了解哪些方法在哪些C ++版本中有效而又不可行将是一个加分.
修改
-
对于我的即时使用,我并不关心性能(我提出了一个大声呼喊的例外!).但是,通常了解各种方法的相对性能将非常有用.
For my immediate usage, I'm not concerned about performance (I'm raising an exception for cryin' out loud!). However, knowing the relative performance of the various methods would be very very useful in general.
为什么不只使用printf本身(C ++毕竟是C的超集...)?此答案讨论了为什么不这样做的一些原因.据我所知,类型安全性是一个很大的原因:如果您将%d放在其中,则所输入的变量最好真的可以转换为整数,因为这就是函数确定其类型的方式.拥有一种使用编译时知识来了解要插入的变量的实际类型的方法会更加安全.
Why not just use printf itself (C++ is a superset of C after all...)? This answer discusses some reasons why not. As far as I can understand, type safety is a big reason: if you put %d, the variable you put in there had better really be convertible to an integer, as that's how the function figures out what type it is. It would be much safer to have a method which uses compile-time knowledge of the actual type of the variables to be inserted.
推荐答案
在C ++ 20中,您将可以使用 std :: format
.
In C++20 you will be able to use std::format
.
这将支持python样式格式:
This will support python style formatting:
string s = std::format("{1} to {0}", "a", "b");
已经有一个实现: https://github.com/fmtlib/fmt .
这篇关于如何构造具有嵌入式值(即“字符串插值")的std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!