C++ 将字符串转换为字符数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13343013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ convert strings to char arrays
提问by xlapa
I want to have 2 strings as input so I can use getline(cin,s)
(so I can pick the whole line until '\n'
) and then I want to search the second array if it contains the word of the first array without using string::find()
or strstr()
.
But I still can't find a way to either convert strings to arrays
我想有 2 个字符串作为输入,以便我可以使用getline(cin,s)
(这样我可以选择整行直到'\n'
),然后我想搜索第二个数组,如果它包含第一个数组的单词而不使用string::find()
or strstr()
。但是我仍然找不到将字符串转换为数组的方法
int main()
{
string s;
string s2;
char array[50];
char array2[50];
cout<<"Give me the first word"<<endl;
getline(cin,s);
cout<<"Give me the text"<<endl;
getline(cin.s2);
array=s;
array2=s2;
}
The second way I was thinking was doing the job from the start with arrays:
我想到的第二种方法是从一开始就使用数组来完成这项工作:
char array[50];
cin.getline(array,50);
But if I use straight arrays is there any way I can find the length of the array like we do on strings?
但是如果我使用直数组,有什么方法可以像我们在字符串上那样找到数组的长度吗?
//example
string s;
int x;
getline(cin,s);
x=line.length();
回答by SingerOfTheFall
Just don't do it, because you don't needto do it.
只是不要这样做,因为您不需要这样做。
You could use the c_str()
function to convert the std::string
to a char array, but in your case it's just unnecessary. For the case of finding elements (which I believe is what you need) you can use the string's operator[]
and treat it as if it was an ordinary array.
您可以使用该c_str()
函数将 the 转换std::string
为 char 数组,但在您的情况下,这是不必要的。对于查找元素(我认为这是您需要的)的情况,您可以使用字符串operator[]
并将其视为普通数组。
回答by dasblinkenlight
You can use c_str
member of the std::string
and strcpy
function to copy the data into the arrays:
您可以使用and函数的c_str
成员将数据复制到数组中:std::string
strcpy
//array=s;
strcpy(array, s.c_str());
//array2=s2;
strcpy(array2, s2.c_str());
However, you don't have to do that unless you must pass non-constant char
arrays around, because std::string
s look and feel much like character arrays, except they are much more flexible. Unlike character arrays, strings will grow to the right size as needed, provide methods for safe searching and manipulation, and so on.
但是,除非您必须传递非常量char
数组,否则您不必这样做,因为std::string
s 的外观和感觉很像字符数组,只是它们更加灵活。与字符数组不同,字符串将根据需要增长到合适的大小,提供安全搜索和操作的方法等。