我想从我的字符串中获取前两个字符。假设我的字符串 dbdir = "Dir"
和我的其他字符串 test = "20122"
。我想从测试中获取前两个字符并将其与 dbdir 字符串组合。所以结果将是 string combined = Dir20 然后我想在文件的另一个字符串中使用组合字符串。
这是我的代码
std::string dbdir = "Dir";
std::string test = "20122";
//strip first two chars from test//
std::string result_of_test_strip = ;
std::string combined = ""+ dbdir + result +"";
CString fileToOpen = "\"\\\\CAR\\VOL1\\Docs\\PRE\\15\\" + result_of_test_strip.c_str() + "\\" + filenum.c_str() + ".prt" + "\"";
建议回答@therainmaker
std::string dbdir = "Dir";
std::string test = "20122";
std::string result = test.substr(0, 2);
std::string combined = dbdir + result;
CString fileToOpen = "\"\\\\CAR\\VOL1\\Docs\\PRE\\15\\" + combined.c_str() + "\\" + filenum.c_str() + ".prt" + "\"";
我在 CString fileToOpen 中收到此错误 --->
error C2110: cannot add two pointers Error executing cl.exe.
最佳答案
您可以使用 substr
函数提取字符串的任何相关部分。
在你的例子中,要提取前两个字符,你可以写
string first_two = test.substr(0, 2) // take a substring of test starting at position 0 with 2 characters
前两个字符的另一种方法可能是
string first_two;
first_two.push_back(test[0]);
first_two.push_back(test[1]);
此外,在您的 string_combined
行中,您不需要在开头和结尾添加空字符串 ""
。以下行也将起作用:
string combined = dbdir + result;
关于c++ - 如何从字符串中获取前两个字符并在另一个字符串中使用这两个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33235572/