c++ - 将 C++ 字符串视为指针

标签 c++ string pointers

免责声明——我来自非常严格的 C 语言背景。

如何使用 STL 和 std::string 而不是 char* 来绕过像这样(公认的荒谬)示例的字符串?

const char* s = "XXXXXXXXhello";
while (*s == 'X') 
    s++;

s += 2;
std::cout << --(--s); //prints `hello`

最佳答案

如果你想做的是修改对象,去掉“h”:

std::string s = "hello";
s = s.substr(1); // position = 1, length = everything (npos)
std::cout << s;  //"ello"

std::string s = "hello";
s.erase(0, 1); // position = 0, length = 1
std::cout << s;  //"ello"

关于c++ - 将 C++ 字符串视为指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35532552/

相关文章:

c++ - std::find 是否仅适用于元素可能未排序的容器?

C++ 模板元编程——根据运行时输入返回一个类型

c++ - Stack around variable is corrupted 错误

c++ - constexpr 中的 std::variant 修改

python - 索引字符串列表

python - 如何修剪字符串 : begin immediately after the first full-stop and end at the last

c++ - 当我从内联函数返回字符串时,会创建多少个临时对象?

c - (size_t)((char *)0) 的计算结果是否为 0?

c - 迭代存储在堆上的数组

c++ - 为什么 C++ 使用指针?