c++ - 如何从字符串中获取前两个字符并在另一个字符串中使用这两个字符

标签 c++ visual-c++

我想从我的字符串中获取前两个字符。假设我的字符串 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/

相关文章:

c++ - 使用 C++ 的 libcurl 中出现 “could not resolve host” 错误

c++ - 用 C 编写的 ffmpeg 程序,无法在 macOS Catalina 10.15.7 中打开我的相机

c++ - 如何计算图像的分辨率?

windows - lockResource() 返回一个指针,但指向未知的结构

visual-studio - 错误 C1083 是否无法打开与整个程序优化相关的编译器生成的文件 'somePath\someFile.cod"?

c++ - 重载下标运算符并使用双指针?

c++ - EXPECT_EQ 错误

c++ - Circle Collider 未检测到其中的点

com - 如何解决调用::UuidToString() 时出现的链接错误?

c++ - 为什么在使用 "C"语言环境时 printf 可以显示非 ASCII 字符?