Hinzu
Hinzu

Reputation: 117

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

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.

Upvotes: 6

Views: 52135

Answers (4)

Nicolae Natea
Nicolae Natea

Reputation: 1194

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
  }

Upvotes: 1

T.Maharani
T.Maharani

Reputation: 118

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.

Upvotes: 2

Ron
Ron

Reputation: 15501

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.

Upvotes: -1

Buddy
Buddy

Reputation: 11028

std::string provides operator[] to access a character by index:

https://en.cppreference.com/w/cpp/string/basic_string/operator_at

Example:

const std::string s("hello");
const char c = s[0];
// c is set to ‘h’

Upvotes: 6

Related Questions