$foo = "PHP";
$bar = "this is a " . $foo . " example.";
有没有类似的东西,还是我必须大量使用strcat
?
$foo = "PHP";
$bar = "this is a " . $foo . " example.";
有没有类似的东西,还是我必须大量使用strcat
?
使用 std::string
相当容易:
std::string foo = "C++";
auto bar = "this is a " + foo + " example.";
确保前两个操作数其中一个是std::string
,而不是都是const char *
或其他类型。
如下所述,此结果将作为CreateProcess
的char *
(LPSTR
)参数使用。 如果参数是const char *
,则c_str()
将是完全可接受的传递方式。 但是,并非如此,这意味着您应该假定它会修改字符串。 MSDN说:
此函数的Unicode版本CreateProcessW可以修改此字符串的内容。
由于这是char *
,显然正在使用CreateProcessA
,因此我认为const_cast<char *>
应该可以工作,但最好还是谨慎些。
您有两个主要选择,一个适用于C++11及更高版本,另一个适用于C++11之前。
std::string
的内部缓冲区现在保证是连续的。 它也保证以空字符结尾。 这意味着您可以传递指向第一个元素的指针:
CreateProcess(..., &str[0], ...);
请确保该函数仅重写内部数组中 [0, size()) 范围内的索引。覆盖保证为 null 终止符的内容是不好的。
std::string
不能保证是连续的或以 null 结尾。我建议创建一个临时的 std::vector
,它保证了连续部分,并将指向其缓冲区的指针传递:
std::vector<char> strTemp(str.begin(), str.end());
strTemp.push_back('\0');
CreateProcess(..., &strTemp[0], ...);
还请注意MSDN:
系统会添加一个空字符来将命令行字符串分隔开文件名和参数。这将原始字符串分成两个字符串进行内部处理。
这似乎表明这里的空终止符不是必需的,但没有大小参数,所以我不能完全确定。
operator+(const char*,operator+(const std::string&,const char*))
。内部返回一个std::string
。 - chris"this is a "+ foo
的结果是作为 result + " example."
的第一个参数使用的。我只是把自己搞糊涂了。 - chris&str[0]
以传递可修改的字符缓冲区,只要它仅覆盖从开头开始的length()
个字符即可。否则,请尝试创建一个std::vector temp(str.begin(), str.end())
并传递&tmp[0]
。如果需要,请确保其以空字符结尾。 - chris是的,你可以使用 std::string
:
std::string foo = "PHP";
std::string bar = std::string("This is a") + foo + std::string(" example.")
#include <string>
,否则你会得到一些错误。 - ᴍᴇʜᴏᴠ在C++中,您可以使用std::string
:
std::string foo = "C++"
std::string bar = std::string("this is a") + foo + " example.";
std::string(...)
来将第一个字符串转换为std::string
,否则它将是一个const char *
,没有operator+
用于连接字符串。
可能还有至少5种其他可能的方法来完成这个任务,就像在C++中几乎总是一样。
[再次打字太慢了]
如果你正在使用带有标准C++库的C++,你可以使用std::stringstream
来完成这个任务。代码看起来应该像这样:
#include <sstream>
std::string const foo("C++");
std::stringstream bar;
bar << "this is a " << foo << " example";
std::string const result(bar.str());
如果由于某些原因您无法使用C++标准库,那么您就不得不使用类似于strcat的函数。
#include <string>
int main() {
std::string foo = "C++";
std::string bar = "this is a " + foo + " example.";
return 0;
}
C++提供了字符串类。
string foo = "PHP";
string bar = string("this is a ") + foo + string(" example.");
std::string
,则该代码将正常工作,但无法连接字符串字面值。不幸的是(或者幸运的是,这取决于你问谁),在C++中,字符串字面值不是std::string
,而是常量字符数组。 - David Rodríguez - dribeas