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
Solved

taking substrings of a string

Posted on 2013-05-18
3
247 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
  • 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

791 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