Mark
Mark

Reputation: 8678

C++ how to extract the first and rest of a string?

Suppose I have a piece of string "abcd" I would like a function to get char 'a' from "abcd" and another function to get "bcd" from "abcd".

Upvotes: 2

Views: 690

Answers (3)

kba
kba

Reputation: 19466

Edited: I realize I was giving a C++.NET example before.

What you're looking for is the substr method. If you have a string s containing "abcd", performing s.substr(0,1) will give you a string containing "a" and s.substr(1,3) will give you a string containing "bcd".

Upvotes: 1

Jonathan Wood
Jonathan Wood

Reputation: 67175

TCHAR s[] = _T("abcd");

// Get 'a'
TCHAR c = s[0];

// Get "bcd"
TCHAR *p = s + 1;

Upvotes: 0

yan
yan

Reputation: 20982

Assuming you're using an std::string, you want:

str[0] // for the first char
str.substr(1) // for the rest of string

If you're using standard C char* strings, you want:

str[0] // for the first char

((char*)str+1) // or
&str[1]        // for the rest of string

When using the former method, ensure you're catching out_of_range exceptions, or are checking for string length in prior to calling it.

Upvotes: 7

Related Questions