M.TwT
M.TwT

Reputation: 73

How to select the nth position from a string vector?

How does one find, let's say, the 2nd position from a string vector?

Here's a string vector example:

1 2 3 4 Hi
7 8 9 0 Bye
2 2 5 6 World

If I use example.at(2), it gives me the whole row 2 2 5 6 World.

I just want to get 2 from the 1st row instead of getting the whole line of 2 2 5 6 World. How do I do that?

Upvotes: 2

Views: 1718

Answers (4)

Remy Lebeau
Remy Lebeau

Reputation: 596417

Other answers show you how to access individual numbers in your strings, but they assume that the numbers are always 1 digit in length. If you ever need to support multi-digit numbers, use std::istringstream() or std::stoi() instead to parse the strings.

Upvotes: 1

Alex Johnson
Alex Johnson

Reputation: 958

This should work:

#include <iostream>
#include <string>
#include <vector>

int main() {
  std::vector<std::string> strings;
  strings.push_back("1234Hi");
  strings.push_back("7890Bye");
  std::cout << strings.at(0)[1] << std::endl; // prints 2
  std::cout << strings.at(1)[1] << std::endl; // prints 8
}

It's sort of like a two-dimensional array: each string you push to the vector is analogous to the first dimension, and then each character of the string is analogous to the second dimension.

But as mentioned above, there may be better ways to do this, depending on what exactly you're trying to do.

Upvotes: 1

FilipRistic
FilipRistic

Reputation: 2821

So what you actually have is vector of string where string represents another dimension, so you have an table with both rows and columns, similar to an 2D array, in other to access a single cell you need 2 indexes, one index for position in vector and another for position in string.

So in your case it would be example[0][0] to get first char of a string in first row, and to get one you are looking for you would need to write example.at(0)[2];

Upvotes: 1

The return value of example.at(2) is the 3rd item in your vector, in this case, a std::string.

To access a specific character in your string, you can use the operator[]. So to select 2 from the first row, you would simply need to do the following:

example.at(0)[2];

Upvotes: 2

Related Questions