指向字符串中的单个字符

Point to a single character within a string

本文关键字:单个 字符 字符串      更新时间:2023-10-16

>假设我有一个名为foo的字符串,其值为"我不想成为c字符串",以及一个名为bar的字符串指针。

有没有办法让 bar 指向字符串中的大写字母 I 而不将其转换为 c 字符串?直接指向它只会给 bar 一个值"我不想成为 c 字符串"而不是值"I",我尝试过的其他一切都只返回错误。

int main() 
{
    string foo = "I dont want to be a c string";
    string *bar = &foo //I want the pointer bar to stay a pointer of type string.
    cout << *bar; //Prints "I dont want to be a c string" when I want it to print "I"
    return 0; //I want bar to point to foo[0].
} 

目标不是打印出 I,而是将 I 的位置提供给字符串类型的指针,而不必将其转换为 cstring。我什至不确定这是否可能。

若要从字符串指针中提取字符,无需执行其他转换。

cout << foo[0];

字符串类具有用于返回字符串的单个字符的特定成员函数。

这应该可以帮助您:

字符* 条形 = &foo[0];
<<酒吧;

指针指向整个字符串。 您需要使其指向单个字符。 这个例子对我有用:

#include <string>
#include <iostream>
int main() 
{
    std::string foo = "I dont want to be a c string";
    char *bar = (char *)foo.c_str();
    std::cout<<*bar; //Prints "I"
    return 0;
}