Author: saqibkhan

  • String Length

    Length of a string is the number of characters present in the string. These characters can be of the data type char, and these include all alphanumeric elements, symbols and miscellaneous characters. In C++ programming language, there are two types of strings- Character Arrays of C-Style type, and String objects which are built-in objects of <string> class.

    The length of a string also includes white spaces, but in case a string includes a terminating character “\0”, the string ends at that character and the count of length is terminated just before that character.

    There are many ways to find the length of a given string. Some of these methods are iterative, whereas some also use in-built functions and methods. These methods are explained clearly in the following parts of this chapter −

    • Using strlen() Method
    • Using string::length() Method of String Class
    • Using string::size() Method of String Class
    • Using Iterative for Loop
    • Using Iterative while Loop

    String Length Using strlen() Method

    Strings are defined as character arrays which are accessed using the pointer to the first iterator of the array. We can use strlen() method of C Library to calculate the length of C-type arrays.

    Syntax

    The following syntax shows how to use strlen() method to calculate the length of the string −

    strlen(string_name);

    Example

    The following example shows how to calculate the length of the string using strlen() method −

    Open Compiler

    #include <bits/stdc++.h>usingnamespace std;intmain(){char s[]="I love TP !!!";
       cout<<"Length of string s : "<<strlen(s);return0;}

    Output

    Length of string s : 13
    

    String Length Using string::size() Method

    Most programmers commonly use string::size() method of string class when there is a need to calculate the length of a string in C++ programming language. It is the most basic method, and it is generally used while traversing a string object.

    Syntax

    The following syntax shows how to use size() method to calculate the length of the string −

    string_object.size();

    Example

    The following example shows how to calculate the length of the string using size() method −

    Open Compiler

    #include <bits/stdc++.h>usingnamespace std;intmain(){
       string s="I love TP !!!\0 and others";
    
       cout<<"Length of string s : "<<s.size();return0;}

    Output

    Length of string s : 13
    

    String Length Using string::length() Method

    We can also use length() method of string class to determine the length of the given string. Both length() and size() methods are part of <string> header file, and these are called as methods to the string object.

    Syntax

    The following syntax shows how to use length() method to calculate the length of the string −

    string_object.length();

    Example

    The following example shows how to calculate the length of the string using length() method −

    Open Compiler

    #include <bits/stdc++.h>usingnamespace std;intmain(){
       string s="I love TP !!!\0 and others";
    
       cout<<"Length of string s : "<<s.length();return0;}

    Output

    Length of string s : 13
    

    String Length Using while Loop

    We can use a simple while loop to iterate over the string and initialize a variable count to calculate the length of the string until we reach the end of the string. For each iteration, the count increases by one, hence the net result will be the length of the string.

    Syntax

    The following syntax shows how to use a while loop to calculate the length of the string −

    while(s[i]!='\0'){[body]}

    Example

    The following example shows how to calculate the length of the string using a single while loop −

    Open Compiler

    #include <bits/stdc++.h>usingnamespace std;intmain(){
       string s="I love TP !!!\0 and others";int count=0, i=0;while(s[i]!='\0') 
    
      count++, i++;
    cout<<"Length of string s : "<<count;return0;}

    Output

    Length of string s : 13
    

    String Length Using a for Loop

    We can use a simple for loop to iterate over the string and initialize a variable count to calculate the length of the string until we reach the end of the string. For each iteration, the count increases by one, hence the net result will be the length of the string.

    Syntax

    The following syntax shows how to use a for loop to calculate the length of the string −

    for(int i=0;s[i]!='\0';i++){[body]}

    Example

    The following example shows how to calculate the length of the string using a single for loop −

    Open Compiler

    #include <bits/stdc++.h>usingnamespace std;intmain(){
       string s="I love TP !!!\0 and others";int count=0;for(int i=0;s[i]!='\0';i++) 
    
      count++;
    cout<<"Length of string s : "<<count;return0;}

    Output

    Length of string s : 13
    
  • User-defined Data Types

    C++ allows the creation of complex data types, such as structs and classes, enabling developers to model real-world entities effectively.

  • Static Typing

    The static type system in C++ helps catch errors at compile time, making code more robust and reducing the risk of runtime errors.

  • Strings

    C++ provides following two types of string representations −

    • The C-style character string.
    • The string class type introduced with Standard C++.

    The C-Style Character String

    The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character ‘\0’. Thus a null-terminated string contains the characters that comprise the string followed by a null.

    The following declaration and initialization create a string consisting of the word “Hello”. To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word “Hello.”

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    

    If you follow the rule of array initialization, then you can write the above statement as follows −

    char greeting[] = "Hello";
    

    Following is the memory presentation of above defined string in C/C++ −

    String Presentation in C/C++

    Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the ‘\0’ at the end of the string when it initializes the array. Let us try to print above-mentioned string −

    Example

    Open Compiler

    #include <iostream>usingnamespace std;intmain(){char greeting[6]={'H','e','l','l','o','\0'};
    
       cout <<"Greeting message: ";
       cout << greeting << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Greeting message: Hello
    

    C Style String Functions

    C++ supports a wide range of functions that manipulate null-terminated strings. These functions are defined in <string.h> header file.

    Sr.NoFunction & Purpose
    1strcpy(s1, s2);Copies string s2 into string s1.
    2strcat(s1, s2);Concatenates string s2 onto the end of string s1.
    3strlen(s1);Returns the length of string s1.
    4strcmp(s1, s2);Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
    5strchr(s1, ch);Returns a pointer to the first occurrence of character ch in string s1.
    6strstr(s1, s2);Returns a pointer to the first occurrence of string s2 in string s1.

    Example

    Following example makes use of few of the above-mentioned functions −

    Open Compiler

    #include <iostream>#include <cstring>usingnamespace std;intmain(){char str1[10]="Hello";char str2[10]="World";char str3[10];int  len ;// copy str1 into str3strcpy( str3, str1);
       cout <<"strcpy( str3, str1) : "<< str3 << endl;// concatenates str1 and str2strcat( str1, str2);
       cout <<"strcat( str1, str2): "<< str1 << endl;// total lenghth of str1 after concatenation
       len =strlen(str1);
       cout <<"strlen(str1) : "<< len << endl;return0;}

    When the above code is compiled and executed, it produces result something as follows −

    strcpy( str3, str1) : Hello
    strcat( str1, str2): HelloWorld
    strlen(str1) : 10
    

    The String Class in C++

    The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality.

    Example of String Class

    Let us check the following example −

    Open Compiler

    #include <iostream>#include <string>usingnamespace std;intmain(){
    
       string str1 ="Hello";
       string str2 ="World";
       string str3;int  len ;// copy str1 into str3
       str3 = str1;
       cout <<"str3 : "<< str3 << endl;// concatenates str1 and str2
       str3 = str1 + str2;
       cout <<"str1 + str2 : "<< str3 << endl;// total length of str3 after concatenation
       len = str3.size();
       cout <<"str3.size() :  "<< len << endl;return0;}

    When the above code is compiled and executed, it produces result something as follows −

    str3 : Hello
    str1 + str2 : HelloWorld
    str3.size() :  10
    

    Creating a String

    We can create string variables in two ways, using either of the following methods −

    Creating String Using Character Arrays

    We can declare strings using the C-type arrays in the format of characters. This is done using the following syntax −

    Syntax

    char variable_name[len_value];

    Here, len_value is the length of the character array.

    Example of Creating String using Character Array

    In the following examples, we are declaring a character array, and assigning values to it.

    Open Compiler

    #include <iostream>usingnamespace std;intmain(){char s[5]={'h','e','l','l','o'};
       cout<<s<<endl;return0;}
    Output
    hello
    

    Creating String using <string>

    We can declare a String variable using the ‘string’ keyword. This is included in the <string> header file. The syntax of declaring a string is explained as follows −

    Syntax

    string variable_name =[value];

    Here, [value] is an optional and can be used to assign value during the declaration.

    Example

    In the following examples, we are declaring a string variable, assigning a value to it.

    Open Compiler

    #include <iostream>usingnamespace std;intmain(){ 
       string s="a merry tale";
       cout<<s;return0;}
    Output
    a merry tale
    

    Traversing a String (Iterate Over a String)

    We can iterate over a string in two ways −

    Using looping statements

    We can traverse a string using for loops, while loops and do while loops using a pointer to the first and the last index in the string.

    Using iterators

    Using range based loops, we can iterate over the string using iterators. This is achieved using “:” operator while running a range based loop.

    Example of Iterating a String

    The following example code shows string traversal using both of these methods −

    Open Compiler

    #include <iostream>usingnamespace std;intmain(){
       string s="Hey, I am at TP.";for(int i=0;i<s.length();i++){
    
      cout&lt;&lt;s&#91;i]&lt;&lt;" ";}
    cout<<endl;for(char c:s){
      cout&lt;&lt;c&lt;&lt;" ";}return0;}</code></pre>

    Output

    H e y ,   I   a m   a t   T P . 
    H e y ,   I   a m   a t   T P . 
    

    Accessing Characters of String

    We can access the characters of a string using both iterators and pointer to the indices of the string.

    Example

    The following example code shows how we can access the characters in a string −

    Open Compiler

    #include <iostream>usingnamespace std;intmain(){
       string s="Hey, I am at TP.";
       cout<<s<<endl;for(int i=0;i<s.length();i++){
    
     s&#91;i]='A';}
    cout<<s<<endl;for(char&c:s){
      c='B';}
    cout<<s<<endl;return0;}

    Output

    Hey, I am at TP.
    AAAAAAAAAAAAAAAA
    BBBBBBBBBBBBBBBB
    

    String Functions

    String is an object of the <string> class, and hence, it has a variety of functions that users can utilize for a variety of operations. Some of these functions are as follows −

    FunctionDescription
    length()This function returns the length of the string.
    swap()This function is used to swap the values of 2 strings.
    size()Used to find the size of string
    resize()This function is used to resize the length of the string up to the given number of characters.
    find()Used to find the string which is passed in parameters
    push_back()This function is used to push the character at the end of the string
    pop_back()This function is used to pop the last character from the string
    clear()This function is used to remove all the elements of the string.
    find()This function is used to search for a certain substring inside a string and returns the position of the first character of the substring.
    replace()This function is used to replace each element in the range [first, last) that is equal to old value with new value.
    substr()This function is used to create a substring from a given string.
    compare()This function is used to compare two strings and returns the result in the form of an integer.
    erase()This function is used to remove a certain part of a string.

    Length of a String

    The length of a string is the number of characters present in the string. Hence, the string "apple" has a length of 5 characters and the string "hello son" has a length of 9 characters (including empty spaces). This can be accessed using the length() method in <string> header file.

    Syntax

    The syntax is explained as follows −

    int len = string_1.length();

    Example

    Open Compiler

    #include <iostream>#include <string>usingnamespace std;intmain(){
       string x="hey boy";
       cout<<x.length()<<endl;return0;}

    Output

    7
    

    String Concatenation

    String concatenation is a way to add two strings together. This can be done using two ways −

    Addition Operator

    The addition operator is used to add two elements. In case of strings, the addition operator concatenates the two strings. This is clearly explained in the following example −

    Example

    Open Compiler

    #include <iostream>#include <string>usingnamespace std;intmain(){
       string x ="10";
       string y ="20";
       cout<<x+y<<endl;return0;}
    Output
    1020
    

    This is different from integer addition. When we take two integers and add them using addition operator, we get the sum of the two numbers instead.

    This is clearly explained in the following example −

    Example

    Open Compiler

    #include <iostream>#include <string>usingnamespace std;intmain(){int x =10;int y =20;
       cout<<x+y<<endl;return0;}
    Output
    30
    

    Using string append() method

    C++ is an object oriented programming language, and hence a string is actually an object, which contain functions that can perform certain operations on strings. We can use string append() method to append one string to another.

    The syntax of this operation is as follows −

    Syntax

    string_1.append(string_2);

    The usage of this method is depicted clearly in the following example −

    Example

    #include <iostream>#include <string>usingnamespace std;intmain(){
       string x="hey boy";
       string y=" now";
       x.append(y);
       cout<<x<<endl;return0;}
    Output
    hey boy now
    

    String Input in C++

    Strings can be taken as an input to the program, and the most common way to do this is by using cin method.

    There are three methods to take a string as an input, and these methods are given as follows −

    • cin
    • getline()
    • stringstream

    Using cin Method

    This is the simplest way to take a string as an input. The syntax is given as follows −

    Syntax

    cin>>string_name;

    Example

    #include <iostream>usingnamespace std;intmain(){
    
       string s;
       cout <<"Enter custom string : "<<endl;//enter the string here
       cin>>s;
       cout<<"The string is : "<<s;}

    Using getline() Method

    The getline() method can be used to read a string from an input stream. This is defined in the <string> header file. The syntax of the above method is given as follows −

    Syntax

    getline(cin, string_name);

    Example

    #include <iostream>usingnamespace std;intmain(){
    
       string s;
       cout <<"Enter String as input : "<< endl;getline(cin, s);//enter the string here
       cout <<"Printed string is : "<< s << endl;return0;}

    Using stringstream

    The stringstream class is used to take multiple strings as input, all at once. The syntax of the above method is given as follows −

    Syntax

    Stringstream object_name(string_name);

    Example

    Open Compiler

    #include <iostream>#include <sstream>#include <string>usingnamespace std;intmain(){
    
       string s ="Hey, I am at TP";
       stringstream object(s);
       string newstr;// >> operator will read from the stringstream objectwhile(object >> newstr){
    
      cout &lt;&lt; newstr &lt;&lt;" ";}return0;}</code></pre>

    Output

    Hey, I am at TP
    
  • Low-level Manipulation

    C++ enables direct manipulation of hardware and memory, which is essential for system-level programming, drivers, and performance-critical applications.

  • Data Abstraction

    C++ allows developers to create abstract data types, which can hide the implementation details and expose only the necessary functionalities, promoting code encapsulation.

  • Compile-time Polymorphism

    Through templates and function overloading, C++ supports compile-time polymorphism, which can improve performance by resolving method calls at compile time instead of runtime.

  • Rich Language Features

    C++ includes advanced features such as operator overloading, exception handling, and namespaces, which allow for more expressive and organized code.

  • Support for Concurrency

    C++11 and later versions offer built-in support for multithreading, making it easier to write concurrent applications that can take advantage of modern multi-core processors.

  • Template Programming

    C++ supports generic programming through templates, enabling code reusability and type safety without sacrificing performance.