Data Structure: String


Hi Everyone , below are the usefull string c++ utilities for making life little easy during competitive programming. Every time picking up the competitive algorithmic programming questions after a small gap (like 30-40 years atleast it seems so) or being out of touch for a while (again like decades) rust the few finger tip codes. Specially Strings (for me atleast). 
Below code snippets are functions which can be clubbed in c++ code , comile & run in terminal.

Below are the Required string operation that need to be handy and by heart remember.
Please do comment if more can be added. Thanks !
Image credit : geeksforgeeks

1.) Hash/map : vector<int>(26) (better efficiency than “map”)
2.) string to int : stoi( str )
3.) int to string : to_string(a)
4.) character to string : std:string(1,a)
5.) sentence to words: istringstream (use for input stream), ostringstream (use for output stream), stringstream(use for input/output both)
6.) Sanitize:
……………….a.) check if character is only alphabet : isalpha(c)
……………….b.) check if character is alphanumberic : isalnum(c)
……………….c.) character to lowercase : tolower(c)
……………….d.) string to lowercase : transform(s.begin(), s.end(), s.begin(), ::tolower); OR for(auto &c : str) c = tolower(c);
……………….e.) check if digit : isdigit(c)
……………….f.) trim : custom code implementation

String Functions Code Block

 

string a = "123";
string b = "123 456";
string c= " 123 ";
string d = "  123 a23";
string e = " a 5432";
        
cout<

 

int a = 123;
char b = 'A';
cout<

 

 

char a = 'T';
cout<< std:string(1,a) ;  // "T"

 

 

//istringstream (use for input stream), ostringstream (use for output stream), stringstream(use for input/output both)

string str = "     bitsofjarvis  ! #  #$%   blog is gooood     ";
istringstream ss(str);
string word;
    while(ss >> word){
    cout< whereas you where waiting a write only object, you will not be happy ;-)
source : stackoverflow

 

string A = "I AM GOOD" , B = "YES I AM";
istringstream combined(A + " " + B);
string word;
 while (getline(combined, word, ' ')){
    cout<

 

 

tolower(c);
OR
for(auto &c : str) c = tolower(c);

 

 

str.substr(startIndex , length);

 

 

str.find("@gmail.com");

OR

 std::string str ("There are two needles in this haystack with needles.");
  std::string str2 ("needle");

  // different member versions of find in the same order as above:
  std::size_t found = str.find(str2);
  if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';

found=str.find("needles are small",found+1,6);
  if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';

  found=str.find("haystack");
  if (found!=std::string::npos)
    std::cout << "'haystack' also found at: " << found << '\n';

  found=str.find('.');
  if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '\n';

  // let's replace the first needle:
  str.replace(str.find(str2),str2.length(),"preposition");
  std::cout << str << '\n';

//output : to be, or not to be: that is the question...

 

 

str.erase (10,8);   
OR
str.erase (str.begin()+5, str.end()-9);

 

 

std::string str="to be question";
  std::string str2="the ";
  std::string str3="or not to be";
  std::string::iterator it;

  // used in the same order as described above:
  str.insert(6,str2);                 // to be (the )question
  str.insert(6,str3,3,4);             // to be (not )the question
  str.insert(10,"that is cool",8);    // to be not (that is )the question
  str.insert(10,"to be ");            // to be not (to be )that is the question
  str.insert(15,1,':');               // to be not to be(:) that is the question
  it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
  str.insert (str.end(),3,'.');       // to be, not to be: that is the question(...)
  str.insert (it+2,str3.begin(),str3.begin()+3); // (or )
  std::cout << str << '\n';
//output:to be, or not to be: that is the question...

 

 

sort(s.begin() , s.end());

 

 

string sentence = "    This   site  is Awsm     GOOOD     ";
stringstream ss(sentence);
string words;
while(ss >> words){
cout<

 

2.) string to int : stoi(str)

string a = "123";
string b = "123 456";
string c= " 123 ";
string d = "  123 a23";
string e = " a 5432";
        
cout<<stoi(a)<<endl;   //123
cout<<stoi(b)<<endl;   //123
cout<<stoi(c)<<endl;   //123
cout<<stoi(d)<<endl;   //123
cout<<stoi(e)<<endl;   //empty

3.) int to string : to_string()

int a = 123;
char b = 'A';
cout<<to_string(a)<<endl;   //"123"
cout<<to_string(b)<<endl;   //65

4.) Character to string

char a = 'T';
cout<< std:string(1,a) ;  // "T"

5.) sentence to words: istringstream (use for input stream), ostringstream (use for output stream), stringstream(use for input/output both)

string str = "     bitsofjarvis  ! #  #$%   blog is gooood     ";
istringstream ss(str);
string word;
    while(ss >> word){
    cout<<word<<endl;
    }
OUTPUT:
bitsofjarvis
!
#
#$%
blog
is
good
string A = "I AM GOOD" , B = "YES I AM";
istringstream combined(A + " " + B);
string word;
 while (getline(combined, word, ' ')){
    cout<<word<<endl;
 }

istringstream is for input, ostringstream for output. stringstream is input and output. You can use stringstream pretty much everywhere. However, if you give your object to another user, and it uses operator >> whereas you where waiting a write only object, you will not be happy 😉
source : stackoverflow

6.) e.) TRIM

std::string & trim(std::string & str)
{
   return ltrim(rtrim(str));
}


std::string & ltrim(std::string & str)
{
  auto it2 =  std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( str.begin() , it2);
  return str;   
}

std::string & rtrim(std::string & str)
{
  auto it1 =  std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( it1.base() , str.end() );
  return str;   
}


1.) string to integer :

stoi(str);

2.) integer to string:

to_string(n);

3.) character to string :

string s = new string(1, c);   

4.) convert to lower case:

tolower(c);
OR
for(auto &c : str) c = tolower(c);

5.) substring :

str.substr(startIndex , length);

6.) find substring :

str.find("@gmail.com");

OR

 std::string str ("There are two needles in this haystack with needles.");
  std::string str2 ("needle");

  // different member versions of find in the same order as above:
  std::size_t found = str.find(str2);
  if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';

  found=str.find("needles are small",found+1,6);
  if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';

  found=str.find("haystack");
  if (found!=std::string::npos)
    std::cout << "'haystack' also found at: " << found << '\n';

  found=str.find('.');
  if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '\n';

  // let's replace the first needle:
  str.replace(str.find(str2),str2.length(),"preposition");
  std::cout << str << '\n';

//output : to be, or not to be: that is the question...

7.) Replace :

str.erase (10,8);   
OR
str.erase (str.begin()+5, str.end()-9); 

8.) Insert :

  std::string str="to be question";
  std::string str2="the ";
  std::string str3="or not to be";
  std::string::iterator it;

  // used in the same order as described above:
  str.insert(6,str2);                 // to be (the )question
  str.insert(6,str3,3,4);             // to be (not )the question
  str.insert(10,"that is cool",8);    // to be not (that is )the question
  str.insert(10,"to be ");            // to be not (to be )that is the question
  str.insert(15,1,':');               // to be not to be(:) that is the question
  it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
  str.insert (str.end(),3,'.');       // to be, not to be: that is the question(...)
  str.insert (it+2,str3.begin(),str3.begin()+3); // (or )
  std::cout << str << '\n';
//output:to be, or not to be: that is the question...

7.) Sort String :

sort(s.begin() , s.end());   

8.) Paragraph to words:

string sentence = "    This   site  is Awsm     GOOOD     ";
stringstream ss(sentence);
string words;
while(ss >> words){
cout<<words<<",";
}
output:
This,site,is,Awsm,GOOOD
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
error

Enjoy this blog? Please spread the word :)

0
Would love your thoughts, please comment.x
()
x