指向字符串中的单个字符
Point to a single character within a string
>假设我有一个名为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;
}
相关文章:
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 为什么char不是单个字符
- C++ 字符串单个字符
- 将单个字符转换为 std::string 前缀 \x01
- 尝试一次将单个字符读取到大小不确定的数组中
- C++ 如何将字符串拆分为单个字符
- 如何在C++中将单个字符哈希为相对较小的素数?
- 如何将像'A'这样的单个字符替换为类似"10"?
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- std::bad_alloc 将文本文件中的单个字符存储到矢量C++中时
- 如何从用户那里获取单个字符,直到他输入"."或输入
- 字符串中单个字符作为数组的数据类型是什么
- 字符串中的重音,如何在单个字符中存储重音字符
- 从字符串中提取单个字符并将其转换为 int
- 如何将单个字符转换为为基本密码哈希器设置整数,C++
- 下推解析器是否扫描令牌或单个字符
- 如何定义一个从任何编码空间解析单个字符的精神 x3 解析器?
- C :占用更多内存,将单个字符作为char或字符串存储
- 如何从字符串中读取单个字符
- WM_GETTEXT只返回单个字符