如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:42:42  来源:igfitidea点击:

How do I get a part of the a string in C++?

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::stringuse substr function.. as Will suggested

如果你的意思是 std::string使用 substr 函数..正如 Will 建议的那样

回答by Alan

Assuming you're using the C++ std::stringclass

假设您使用的是 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_swhich is the first i-ththe element in s.

它创建一个字符串sub_of_s,它是 中的第i-th一个元素s