Solved

taking substrings of a string

Posted on 2013-05-18
3
251 Views
Last Modified: 2013-05-18
Why this little code doesn't work?I want to take a string and then assign substrings to another string.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x = "ALERT";

string y = x[0] + x[1];   
cout << y;    //PRINT AL
return 0;
}

Open in new window

0
Comment
Question by:codeBuilder
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 32

Expert Comment

by:phoffric
ID: 39177182
0
 
LVL 32

Accepted Solution

by:
phoffric earned 250 total points
ID: 39177188
x[0] returns char, and + on char doesn't mean concatenate. It means add the two char numbers together.
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 250 total points
ID: 39177233
Since phoffric has elaborated why your attempt does not work, here's what would work - and it's surprisingly close to your question title:

#include <iostream>
#include <string>
using namespace std;
int main()
{
string x = "ALERT";

string y = x.substr(0,2);   // 1st parameter is start position, 2nd is length
cout << y;    //PRINT AL
return 0;
}
                                  

Open in new window


See also http://en.cppreference.com/w/cpp/string/basic_string/substr and http://en.cppreference.com/w/cpp/string/basic_string
0

Featured Post

[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question