C++将字符串的元素分配给新字符串
我试图将一段字符串分配给一个新的字符串变量。现在我很新,所以时间更长了,但更容易理解的解释对我来说是最好的。无论如何,我尝试做的事情是这样的:
string test = "384239572";
string u = test[4];
我尝试做的完整代码是这样的:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string test = "384239572";
string u = test[4];
int i = 0;
istringstream sin(u);
sin >> i;
cout << i << endl;
return 0;
}
尽管它似乎在抱怨我放在那里的上部部分。那么如何从字符串中取出字符串的一小部分,并将其分配给新字符串呢?预先非常感谢!如果您知道任何好的链接或与此相关的任何内容,我们也将不胜感激!
Im trying to assign a piece of a string, to a new string variable. Now Im pretty new so longer, but easier to understand explanations are the best for me. Anyways, how Im trying to do it is like this:
string test = "384239572";
string u = test[4];
The full code of what im trying to do is this:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string test = "384239572";
string u = test[4];
int i = 0;
istringstream sin(u);
sin >> i;
cout << i << endl;
return 0;
}
Though it seems to complain at the upper part that I put up there. So how can I take a small part of a string from a string, and assign it to a new string? Thanks a lot in advance! If you know any good links or anything about this, that would be appreciated too!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用子字符串,
use substring,
您可以使用字符串 构造函数 之一
编辑: 1 表示重复字符测试的次数[4]
在您的代码中,您尝试将
char
分配给string
对象。You can use one of the string constructors
EDIT: The 1 indicates the number of times to repeat the character test[4]
In your code you are trying to assign a
char
to astring
object.string
类有一个方法substr()
在这里很有用:这可以很好地推广到任意长度的子字符串。
The
string
class has a methodsubstr()
that would be useful here:This generalizes nicely to substrings of any length.