C ++将字符串转换为char数组 [英] C++ convert strings to char arrays
问题描述
我想输入2个字符串,因此可以使用 getline(cin,s)
(这样我就可以选择整行,直到' \n'
),然后我想搜索第二个数组是否包含第一个数组的单词,而不使用 string :: find()
或 strstr()
。
但是我仍然找不到将字符串转换为数组的方法
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
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();
推荐答案
请不要这样做,因为您不会t 需要做到这一点。
Just don't do it, because you don't need to do it.
您可以使用 c_str()
函数将 std :: string
转换为char数组,但是在您的情况下这是不必要的。对于查找元素的情况(我认为这是您所需要的),可以使用字符串的 operator []
并将其视为普通数组。
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 ++将字符串转换为char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!