String Datatype in C++

String Initialisation 

By default string can be initialised to "" (empty string).

There are 3 methods to initialise the variables:


string
 s = "aba" // method 1

string s{"abc"};  // method 2


Click here to learn initialising string from other characters of the string.

Initialising string from the array of characters. Click here to debug.
#include <iostream>

using namespace std;

int main()
{
    char arr[] = {"shirley"};
    string s = "";
    
    //cout << "array arr " << arr << endl;
    
    for (int i = 0; i < sizeof(arr); i++) {
        s += arr[i];
    }
    //cout << "String s " << s << endl;
    return 0;
}

String Declaration 

string s;

Printing the String 

cout<<" string " << s;
    // Printing the string
    cout<< "string " << s << endl;
    cout << "s1 " << s1 << " s2 " << s2 << endl;

using Lambda

auto print = [] (auto const& v) {
   cout << "Print using Lambda" << endl;
   for (const auto& e:v) { cout << e;} 
   cout << endl;
};

In main()
    // Print using lambda 
    print(s);

Reading the String 

// Reading from the user
cin >> s;

Click here to know how to read a string.

String Sanitisation

There are three ways to do string empty check:

2. s.size() == 0
3. strlen(s.data()) == 0

#include <iostream>
#include <cstring>

using namespace std;

/* User defined function to check 
  the string length using size() */
bool checkEmptyStringS(const string &s) 
{
        return s.size() == 0;
}

/* User defined function to check 
  the string length using length() */
bool checkEmptyStringS1(const string &s) 
{
        return s.length() == 0;
}

/* User defined function to check 
  the string length using strlen */
bool checkEmptyStringS2(const string &s) 
{
        return strlen(s) == 0;
}

int main()
{
    //String declaration
    string s;
    
    //String Initialisation
    string s1 = "abc";
    string s2{"def"};
    
    // Check if the string is empty using built-in function
    if (s.empty()) {
        cout << "\nString s is empty." << endl;
    }
    
    cout << "Enter the user name: ";
    // Reading from the user 
    cin >> s;
    
    // Check if the string is empty using user defined function
    checkEmptyStringS(s) ? 
         cout << "\nString s is still empty." << endl : 
         cout << "\nString s is not empty, now." << endl;  
  
    checkEmptyStringS1(s1) ? 
         cout << "\nString s1 is empty." << endl : 
         cout << "\nString s1 is not empty." << endl; 
       
    checkEmptyStringS2(s2) ? 
         cout << "\nString s2 is empty." << endl : 
         cout << "\nString s2 is not empty." << endl; 
         
    
    return 0;
}

Output:
1
2
3
In function 'bool checkEmptyStringS2(const std::string&)':
Line 24: error: cannot convert 'const std::basic_string<char, std::char_traits<char>, std::allocator<char> >' to 'const char*' for argument '1' to 'size_t strlen(const char*)'
compilation terminated due to -Wfatal-errors.

strlen() accepts const char *, s.data() is const char *

#include <iostream>
#include <cstring>

using namespace std;

/* User defined function to check 
  the string length using size() */
bool checkEmptyStringS(const string &s) 
{
        return s.size() == 0;
}

/* User defined function to check 
  the string length using length() */
bool checkEmptyStringS1(const string &s) 
{
        return s.length() == 0;
}

/* User defined function to check 
  the string length using strlen */
bool checkEmptyStringS2(const string &s) 
{
        return strlen(s.data()) == 0;
}

int main()
{
    //String declaration
    string s;
    
    //String Initialisation
    string s1 = "abc";
    string s2{"def"};
    
    // Check if the string is empty using built-in function
    if (s.empty()) {
        cout << "\nString s is empty." << endl;
    }
    
    cout << "Enter the user name: ";
    // Reading from the user 
    cin >> s;
    
    // Check if the string is empty using user defined function
    checkEmptyStringS(s) ? 
         cout << "\nString s is still empty." << endl : 
         cout << "\nString s is not empty, now." << endl;  
  
    checkEmptyStringS1(s1) ? 
         cout << "\nString s1 is empty." << endl : 
         cout << "\nString s1 is not empty." << endl; 
       
    checkEmptyStringS2(s2) ? 
         cout << "\nString s2 is empty." << endl : 
         cout << "\nString s2 is not empty." << endl; 
         
    
    return 0;
}

Output:
1
2
3
4
5
6
7
8
String s is empty.
Enter the user name: Shirley
String s is not empty, now.

String s1 is not empty.

String s2 is not empty.

String Comparison "str1.compare(str2)"


String sort

How to implement your own sort method for strings ?

    string strSort(string s) {
        int counter[26] = {0};
        for (char c : s) {
            counter[c - 'a']++;
        }
        string t;
        for (int c = 0; c < 26; c++) {
            t += string(counter[c], c + 'a');
            //cout << string(counter[c], c + 'a') << endl;
            //cout << t << endl;
        }
        //cout << t << endl;
        return t;
    }

s.substr(startInd, length)


Passing the string to a function 


with reference 




Return the string from a function 





String concatenation 



Find all positions of the specific  char in the string 

https://thispointer.com/find-all-occurrences-of-a-sub-string-in-a-string-c-both-case-sensitive-insensitive/


string to uppercase (transform)

https://stackoverflow.com/questions/23418390/how-to-convert-a-c-string-to-uppercase


Program 

Debug using this link

#include <iostream>

using namespace std;

auto print = [] (auto const& v) {
   cout << "Print using Lambda" << endl;
   for (const auto& e:v) { cout << e;} 
   cout << endl;
};

int main()
{
    //String declaration
    string s;
    
    //String Initialisation
    string s1 = "abc";
    string s2{"def"};
    
    // Reading from the user 
    cin >> s;
    
    // Printing the string
    cout<< "string " << s << endl;
    cout << "s1 " << s1 << " s2 " << s2 << endl;

    // Print using lambda 
    print(s);
    
    return 0;
}


Output:


hello
string hello
s1 abc s2 def
Print using Lambda
hello

Single Program Altogether

#include <iostream>
#include <cstring>
#include <vector>

int main()
{
    /* Copy initialisation using copy constructor of string */
    std::string str = "rose";
    /* Direct initialisation */
    std::string str2("shirley");
    std::cout << "str     " << str << " str2   " 
              << str2 <<std::endl;
    
    std::string str22(str2.begin(), str2.end());
    std::cout << "str22   " << str22 << std::endl;
              
    /* String initialisation by assigning specific
       indices of other string */
    std::string str3(str2, 3, 6);
    std::cout << "str3    " << str3 << " str2   " 
              << str2 <<std::endl;
              
    /* Operator Overloading */
    std::string str4 = str2 + " is trying to"
     " unravel certain problems";
    std::cout << "str4    " << str4 << std::endl;
    
    /* Get the substring of 10 letters from 10th index 
       substr(index, noOfLetters) */
    std::string str5 = str4.substr(11, 10);
    std::cout << "str5    " << str5 << std::endl;
    
    /* Convert string to const char* - Method 1 */
    std::string str6 = "hello";
    const char *c = str6.c_str();
    std::cout << "char    " << c << std::endl;
    
    /* Convert string to char* - Method 2 */
    std::string str7 = "world";
    char *c1 = new char[str7.length()];
    strcpy(c1, str7.c_str());
    std::cout << "char    " << c1 << std::endl;
    delete []c1;
    
    /* Convert string to vector of chars - Method 3 */
    std::vector<char> v1(str7.begin(), str7.end());
    for (auto &c : v1) {
         std::cout << c << " ";
    }
    std::cout  << std::endl;
    
    /* Convert string to char - Method 4 */
    std::string str8 = "bellow";
    char c2 = str8[0];
    std::cout << "char    " << c2 << std::endl;
    
    
    return 0;
}

Output:


str     rose str2   shirley

str22   shirley

str3    rley str2   shirley

str4    shirley is trying to unravel certain problems

str5    trying to 

char    hello

char    world

w o r l d 

char    b

Click here to debug.






Comments