C++ tutorial-substr function


C++ String Manipulation

C++ substr() and empty functions


You can use substr(start, num_chars) function to get a proportion in num_chars length with the starting point specified as the start arguemnt of a string. To check whether a string is empty before taking part of the string out, you can use empty() function.

Example:

#include <cstdlib>
#include <iostream>
#include <conio.h>


using namespace std;
void strmanip(){
  string name;
  cout<<"Enter your full name separating by underscore:";
  cin>>name;
  if(!name.empty()){

   //find the position of "_"
   int pos_space=name.find("_");

   //take first name out
   cout<<"Your first name is:"<<name.substr(0,pos_space)<<endl;

   //take last name out
   cout<<"Your last name is:"<<name.substr(pos_space+1,name.size()-pos_space)<<endl;

}
  else cout<<"Your name is empty."<<endl;

}

int main(){

   strmanip();
   getch();
   return 0;

}


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.