如何在 C++ 中获取 a 字符串的一部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2498119/
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
How do I get a part of the a string in C++?
提问by small_potato
How do I get a part of a string in C++? I want to know what are the elements from 0 to i.
如何在 C++ 中获取字符串的一部分?我想知道从 0 到 i 的元素是什么。
回答by Will
You want to use std::string::substr
. Here's an example, shamelessly copied from http://www.cplusplus.com/reference/string/string/substr/
您想使用std::string::substr
. 这是一个例子,无耻地从http://www.cplusplus.com/reference/string/string/substr/复制而来
// string::substr
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str="We think in generalities, but we live in details.";
// quoting Alfred N. Whitehead
string str2, str3;
size_t pos;
str2 = str.substr (12,12); // "generalities"
pos = str.find("live"); // position of "live" in str
str3 = str.substr (pos); // get from "live" to the end
cout << str2 << ' ' << str3 << endl;
return 0;
}
回答by paxdiablo
You use substr
, documented here:
您使用substr
,记录在此处:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cout << "Enter string (5 characters or more): ";
cin >> a;
if (a.size() < 5)
cout << "Too short" << endl;
else
cout << "First 5 chars are [" << a.substr(0,5) << "]" << endl;
return 0;
}
You can also then treat it as a C-style string (non-modifiable) by using c_str
, documented here.
然后,您还可以通过使用 将其视为 C 样式字符串(不可修改)c_str
,记录在此处。
回答by raj
if u mean string is an array of characters,
如果你的意思是字符串是一个字符数组,
char str[20];
int i;
strcpy(str,"Your String");
//Now lets get the substr
cin>>i;
// do some out-of-bounds validation here if u want..
str[i+1]=0;
cout<<str;
if u mean the std::string
use substr function.. as Will suggested
如果你的意思是 std::string
使用 substr 函数..正如 Will 建议的那样
回答by Alan
Assuming you're using the C++ std::string
class
假设您使用的是 C++std::string
类
you can do:
你可以做:
std::string::size_type start = 0;
std::string::size_type length = 1; //don't use int. Use size type for portability!
std::string myStr = "hello";
std::string sub = myStr.substr(start,length);
std::cout << sub; //should print h
回答by an offer can't refuse
use:
用:
std::string sub_of_s(s.begin(), s.begin()+i);
which create a string sub_of_s
which is the first i-th
the element in s
.
它创建一个字符串sub_of_s
,它是 中的第i-th
一个元素s
。