1

如何在 C++ 中获取字符串或数组或向量的特殊部分?在python中是这样的:

a = "hello"     #string
b = [1,2,3,4,5]     #list
a[1:4]     #from index 1 to 4
b[2:4]     #from index 2 to 4

结果:

"ell"
[3,4]

C++ 有这样的语法吗?

4

6 回答 6

2

string你可以对子字符串做同样的事情

 string a = "hello";
 string special = a.substr(1,3);
 //you get ell

对于向量,您可以执行以下操作:

vector<int> b{1,2,3,4,5};
vector<int> sepcial(b.begin()+2, b.begin() + 4);
//you get [3,4]
于 2013-04-21T20:25:30.050 回答
2

在C++ std::string上阅读一个很好的参考页面

你可能想要

 std::string s = "Hello";
 std::string e = s.substr(1,3);

然后e得到"ell".

而且我不称其为特殊语法,而是一些标准库 API。

于 2013-04-21T20:25:40.997 回答
2

有关适用于所有容器的更通用的版本,请参见例如std::copy

例如,这可用于将部分向量中的某些项目复制到新向量中:

std::vector<int> b = { 1, 2, 3, 4, 5 };

std::vector<int> sub;
std::copy(std::begin(b) + 2,  // Start at "index" 2
          std::begin(b) + 5,  // Copy until (but NOT including) index 5
          std::back_inserter(sub)); // `back_inserter` calls `push_back` on `sub`

在此之后,向量sub将包含列表 3、4、5。

要了解有关迭代器函数的更多信息,您可以阅读例如此参考


如果您想复制 N 个条目,而不必使用第一个/最后一个,您可以使用std::copy_n

std::copy_n(std::begin(b) + 2,  // Start at "index" 2
            3,                  // Copy three items
            std::back_inserter(sub)); // `back_inserter` calls `push_back` on `sub`

结果将是相同的。

于 2013-04-21T20:32:09.990 回答
2

您可以使用substr字符串的方法:

 string a = "abcdef";
 string special = a.substr(1,3); // gets bcd

对于slicevalarrays:

#include <iostream>
#include <valarray>
using namespace std;

int main ()
{
  valarray<int> foo (5);
  for (int i=0; i<5; ++i) foo[i]=i;

  valarray<int> bar = foo[slice(2,3,1)];

  cout << "slice(2,3,1): ";
  for (size_t n=0; n<bar.size(); n++)
      cout << bar[n] << ' ';
  cout << endl;

  return 0;
}
// Output: slice: 2,3,4

向量和copy列表的算法:

#include <iostream>
#include <algorithm>
#include <vector>

int main () {
  int myints[]={1,2,3,4,5};
  std::vector<int> v (5);

  std::copy ( myints+1, myints+4, v.begin() );

  std::cout << "v contains:";
  for (std::vector<int>::iterator it = v.begin(); it!=v.end(); ++it)
    std::cout << ' ' << *it;

  std::cout << '\n';

  return 0;
}
// output 2,3,4
于 2013-04-21T20:38:55.903 回答
1

这取决于您实际使用的是什么。

有两种不同类型的“字符串”,c++string类和标准 C-String。

C-String 基本上是一个字符数组,因此您可以使用这样的 for 循环对其进行迭代:

for(int i = Begin; i < Max; ++i) printf("%c", a[i]);

或者,您可以这样做:

printf("%3s", &a[Begin]);

其中 3 是您想要的字符数......但是要使其正常工作,您必须在编译时知道您想要的字符串部分(或使用 sprintf.

如果您想使用 C++ string,您可以使用该substr函数。

string a = "hello";
string b = a.substr(1, 4);  //b is 'ello'
于 2013-04-21T20:26:48.187 回答
1

您要完成的是从字符串中提取字符串。也称为子字符串。

在 C++ 中,std::string 类促进了这种能力。

请参阅 std::string 类中的 substr 成员函数。(http://www.cplusplus.com/reference/string/string/substr/

一个简单的例子:

void some_fuction() {
  std::string my_string("Hello");
  std::string my_sub_string(my_string.substr(1, 3)); // Will contain "ell"
}
于 2013-04-21T20:29:49.163 回答