[英]write to string array char by char
i'm working on a project and i came to a deadlock. 我正在做一个项目,但陷入僵局。 i'm having trouble figuring out how to write a string char by char in an array?
我在弄清楚如何在数组中按char编写字符串char时遇到问题?
i mean: 我的意思是:
string my_str[10];
i want to access my_str[0]'s first char. 我想访问my_str [0]的第一个字符。
i tried this: 我尝试了这个:
string tokens[10];
(&tokens[0])[0] = 'a';
(&tokens[0])[1] = 's';
(&tokens[0])[2] = 'd';
it works like tokens[0]='a', tokens[1]='s' etc. 它的工作方式类似于tokens [0] ='a',tokens [1] ='s'等。
then i tried: 然后我尝试了:
string tokens[10];
(&tokens[0])[0][0] = 'a';
(&tokens[0])[0][1] = 's';
(&tokens[0])[0][2] = 'd';
when i compile it errors (string substring out of range) but when i click abort it works. 当我编译它时出错(字符串子字符串超出范围),但是当我单击中止时它起作用了。 what is wrong with this code?
此代码有什么问题?
If you want to add a character at a time to a string, you can use either push_back
or the +=
operator. 如果要一次向字符串添加字符,则可以使用
push_back
或+=
运算符。 Eg: 例如:
tokens[0] += 'a';
tokens[0] += 's';
tokens[0].push_back('d');
The string you created using 您使用创建的字符串
string tokens[10];
are empty. 是空的。 That is, you have 10 empty
string
s. 也就是说,您有10个空
string
s。 If you want to access a character in there you'll need to resize them, eg: 如果要访问其中的字符,则需要调整它们的大小,例如:
string tokens[10];
for (string& str: tokens) {
str.resize(3);
}
tokens[0][0] = 'a';
tokens[0][1] = 's';
tokens[0][2] = 'd';
When you use, eg, 当您使用例如
(&tokens[0])[2] = 'd';
you first get a pointer to the first string
in the array, dereference that index 2
, and assign a string
which is converted from the character 'd'
, ie, string('d')
to it. 首先得到一个指向所述第一
string
数组中,解除引用该索引2
,并指定一个string
,其从字符转换'd'
,即string('d')
到它。 That is, this statement is equivalent to 也就是说,此语句等效于
token[2] = 'd';
You'll want to use string::at for this. 您将为此使用string :: at。 Like so:
像这样:
char x;
string s[10];
s[0] = "asdf";
x = s[0].at(0);
printf("%c", x);
prints a. 打印一个。
You can use the public member function in the String class name : c_str(). 您可以在String类名称中使用public成员函数:c_str()。 It returns in fact Returns a pointer to an array that contains a null-terminated sequence of characters (ie, a C-string) representing the current value of the string object: to be specific, it's a char array that contains the exact equivalent of the string object value.
实际上,它返回一个指向数组的指针,该数组包含一个以null终止的字符序列(即,C字符串),该字符串表示字符串对象的当前值:具体来说,它是一个char数组,其中包含与字符串对象的值。 Let's say we have a :
假设我们有一个:
string array_of_strings[10];
To access the first char of array_of_strings[0] and print it is simply to write: 要访问array_of_strings [0]的第一个字符并打印,只需编写以下命令:
std::cout << array_of_strings[0].c_str()[0] << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.