How to get letter from String by index? C++

Viewed 22463

Can someone briefly explain how to get a character from index from String in C++.

I need to read the first 3 letters of a String and in java it would bestr.charAt(index) and I have been searching the internet for a solution for 2h now and still don't understand...

can some one please give me an example.

4 Answers

Best place to look would be cpluspluc.com: http://www.cplusplus.com/reference/string/string/

You may use as earlier mentioned: http://www.cplusplus.com/reference/string/string/operator[]/

  std::string str ("Test string");
  for (int i=0; i<str.length(); ++i)
  {
    std::cout << str[i];
  }

Or better yet: http://www.cplusplus.com/reference/string/string/at/

  std::cout << str.at(i);

which also checks for a valid position and throws an out of range exception otherwise.

Alternatively you could use http://www.cplusplus.com/reference/string/string/data/ to acces the raw data.

Or if you want to check that your string starts with a specific pattern: http://www.cplusplus.com/reference/string/string/rfind/

  std::string str = "Hey Jude!";
  if (str.rfind("Hey", 0) == 0) {
    // match
  }

substr() It returns a newly constructed string object with its value initialized to a copy of a substring of this object.

Syntax substr(pos, pos+len)

Code

std::string str ("Test string"); //string declaration
string sub_string = str.substr(0,3); 

String index starts from 0.

Another option to obtain a single character is to use the std::string::at() member function. To obtain a substring of a certain length, use the std::string::substr member function.

Related