如何访问字符串的元素?

How do I access the elements of a string?

本文关键字:字符串 元素 访问 何访问      更新时间:2023-10-16

我在访问二进制字符串的各个字符以查明它们是否已设置时遇到问题,我做错了什么?还是有更简单的方法?这是我的代码:

#include <iostream>
#include <string>
using namespace std;
float BinToDec(const string & bin) {
short length = bin.length();
float result = 1.0f;
const char * str = bin.c_str();
for (int i = 0; i < length; ++i) {
if ( &str[i] == "1") cout << "SET" << endl << endl;
else cout << "NOT SET" << endl << endl;
}
return result;
}
int main() {
string bin = "";
cout << "Input a binary number: ";
cin >> bin;
cout << BinToDec(bin) << endl << endl;
}

你可以直接迭代你的字符串bin,不需要获取const char *,这里也不需要&运算符,因为通过使用[]你已经取消引用并得到一个char(这就是为什么你不应该将其与不是字符而是string literal的"1"进行比较)

总而言之,我认为这将是一个更好的方法:

for (int i = 0; i < length; ++i) {
if ( bin[i] == '1') 
cout << "SET" << endl << endl;
else 
cout << "NOT SET" << endl << endl;
}

此外,将长度存储在short中现在可能有效,但存在长度超过最大值的字符串short,因此您应该使用size_t.

它不适合您,因为:

  • 您正在尝试获取一个子字符串以与字符串"1"进行比较,但是您的子字符串将在输入结束时终止...即可能远远超过1字符。
  • 将 C 字符串与==进行比较只是比较指针值

相反,只比较单个字符:

if ( str[i] == '1') cout << "SET" << endl << endl;
//  ^          ^ ^
//  |        character literals are delimited by _single_ quotes
// no `&` required

但我完全不明白你为什么要使用.c_str();直接在bin上操作,而不是创建这个 C 字符串str

float BinToDec(const string& bin)
{
size_t length = bin.length();
float result = 1.0f;
for (int i = 0; i < length; ++i) {
if (bin[i] == '1')
cout << "SET" << endl << endl;
else
cout << "NOT SET" << endl << endl;
}
return result;
}

我还更正了length的类型。

如果您确定要使用 C 样式字符串执行此操作,请更改:

if ( &str[i] == "1") cout << "SET" << endl << endl;

if ( str[i] == '1') cout << "SET" << endl << endl;

这样,您就可以将str的单个字符与'1'、文字字符(而不是"1"包含 1 个字符的字符串)进行比较。

您现有的代码将偏移量 i 的地址放入 c_str(),这实际上与从字符 i 开始的字符串的末尾相同,并将其与文本字符串"1"进行比较。 请注意,您不能像这样进行 C 样式的字符串比较,因为它会比较底层指针。

由于您正在尝试检查每个字符的值,因此请使用单引号而不是双引号。

float BinToDec(const string & bin) {
short length = bin.length();
float result = 1.0f;
const char * str = bin.c_str();
char c; 
for (int i = 0; i < length; ++i) {
c = str[i];
// Use single quotes and not double quotes here
if ( c == '1') cout << "SET" << endl << endl;
else cout << "NOT SET" << endl << endl;
}
return result;
}

也就是说,我认为lccarrasco的方式是实现你想要实现的目标的正确方式。