C++ Strings

Strings are a fundamental data type, serving as the building blocks for text manipulation and processing. In C++, a string is a sequence of characters, enclosed within double quotation marks. C++ supports two types of String representations:

  • C Strings (terminated by a null character('\0'))
  • Objects of string class (C++ Library provides a string class)


C Strings

String in C programming language is a one-dimensional array of characters which is terminated by a null character('\0'). A character array which is not null terminated is not a valid C string. In a C string, each character occupies one byte of memory including null character.

Null character marks the end of the string, it is the only way for the compiler to know where this string is ending.

Examples of C Strings
  • "A"
  • "TechCrashCourse"
  • "Tech Crash Course"
  • " "
Memory representation of C string C++ String memory representation

Declaration of C Strings

Syntax of String Declaration
char string_name[SIZE_OF_STRING];

In the above declaration, string_name is a valid C identifier which can be used later as a reference to this string. Remember, name of an array also specifies the base address of an array.SIZE_OF_STRING is an integer value specifying the maximum number of characters which can be stored in this string including terminating null character. We must specify size of string while declaration if we are not initializing it.

For Example:
char address[100];
char welcomeMessage[200];

Initialization of C Strings

Initialization of string using a character array
char name[16] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
or
char name[] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};

In the above declaration individual characters are written inside single quotes('') separated by comma to form a list of characters which is wrapped in a pair or curly braces. This list must include a null character as last character of the list.

If we don't specify the size of String then length is calculated automatically by the compiler.

Initialization of string using string literal
char name[16] = "TechCrashCourse";
or
char name[] = "TechCrashCourse";

In above declaration a string with identifier "name" is declared and initialized to "TechCrashCourse". In this type of initialization, we don’t need to put terminating null character at the end of string constant. C compiler will automatically inserts a null character('\0'), after the last character of the string literal.


C++ Program for String Initialization

#include <iostream>
using namespace std;

int main(){  
   char nameOne[16] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
   char nameTwo[] = {'T','e','c','h','C','r','a','s','h','C','o','u','r','s','e','\0'};
   char nameThree[16] = "TechCrashCourse";
   char nameFour[] = "TechCrashCourse";
   char *nameFive = "TechCrashCourse";
   char nameSix[16];
   
   cout << nameOne << endl; 
   cout << nameTwo<< endl; 
   cout << nameThree << endl; 
   cout << nameFour << endl; 
   cout << nameFive << endl; 
   
   // Taking string input from user 
   cout << "Enter a string \n";
   cin >> nameSix;
   cout << "You Entered : " << nameSix;
    
   return 0; 
}
Output
TechCrashCourse
TechCrashCourse
TechCrashCourse
TechCrashCourse
TechCrashCourse
Enter a string
C++
You Entered : C++

String Handling Standard Library Functions in C++

cstring header file contains a wide range of functions to manipulate null-terminated C strings. Below are some commonly used string handling functions of cstring header file.

Function Description
strlen() It returns the length of a string.
strcat() It appends one string at the end of another string.
strcpy() It copies characters from one string into another string.
strcmp() It compares two strings character by character.
strtok() It breaks a string into smaller tokens.
strchr() It searches for the first occurrence of a character in the string.
strstr() It searches for the first occurrence of a string in another string.
#include <iostream>
#include <cstring>
using namespace std;
 
int main(){
   char input[50];
   char copyString[60];
    
   cout << "Enter a string\n";
   cin >> input;
 
   // Printing length of string using strlen()
   cout << "Length of string : " << strlen(input) << endl;
 
   // copying input into copyString
   strcpy(copyString, input);
   cout << "Copied String : " << copyString << endl;
 
   // comparing input and copyString string
   if(strcmp(copyString, input)){
       cout << "Both Strings are Not Equal\n";
   } else {
       cout << "Both Strings are Equal\n";
   }
   
   return 0;
}
Output
Enter a string: TechCrashCourse
Length of TechCrashCourse : 15
Copied String : TechCrashCourse
Both Strings are Equal
Points To Remember
  • Null character marks the end of the C strings.
  • C Strings are single dimensional array of characters ending with a null character(‘\0’).
  • The ASCII value of null character('\0') is 0.
  • Each character of string is stored in consecutive memory location and occupy 1 byte of memory.
  • Strings constants are enclosed by double quotes and character are enclosed by single quotes.
  • If the size of a C string is N, it means this string contains N-1 characters from index 0 to N-2 and last character at index N-1 is a null character.

String Class in C++

C++ provides a String class, you can also create a objects of string class for holding strings. String class supports all the operations mentioned above, additionally much more functionality.At this point may not understand about classes and object, until you understand the Object Oriented Programming Concepts(which is discussed later). Here is a sample C++ program using string class.

#include <iostream>
#include <cstring>

using namespace std;

int main () {
   // Declaring objects of string class
   string strOne = "C++";
   string strTwo = "Programming";
   string strThree;
   int length;

   // Reading string from user 
   cout << "Enter a string\n";
   getline(cin, strThree);
   
   // Printing String 
   cout << strThree<< endl;;
   // concatenating strOne and strTwo
   strOne = strOne + strTwo;
   cout << "Combined String : " << strOne << endl;

   // Printing length of string 
   length = strOne.size();
   cout << "Length of Combined String : " << length << endl;

   return 0;
}
Output
Enter a string
TechCrashCourse
TechCrashCourse
Combined String : C++Programming
Length of Combined String : 14

Best Practices for Working with Strings in C++

  • Use std::string for Flexibility : Prefer using std::string over C-style strings for better safety and flexibility.
    #include <iostream>
    #include <string>
    
    int main() {
        // Using std::string for flexibility
        std::string cppString = "C++ is powerful!";
    
        // Displaying the string
        // Output: C++ is powerful!
        std::cout << cppString << std::endl; 
    
        return 0;
    }
    
    std::string automatically manages memory and provides useful member functions.

  • Be Mindful of Null-Termination in C-Style Strings : When working with C-style strings, be mindful of null-termination, and ensure that strings are properly null-terminated.
    #include <iostream>
    #include <cstring>
    
    int main() {
        // Mindful handling of null-termination
        const char* cString = "Hello, World!";
    
        // Displaying the C-style string
        std::cout << cString << std::endl; // Output: Hello, World!
    
        return 0;
    }
    

  • Use std::getline for Input : When accepting string input from the user, prefer using std::getline over std::cin to handle spaces and prevent buffer issues.
    #include <iostream>
    #include <string>
    
    int main() {
        // Using std::getline for input
        std::string userInput;
    
        std::cout << "Enter a sentence: ";
        std::getline(std::cin, userInput);
    
        // Displaying the entered sentence
        std::cout << "You entered: " << userInput << std::endl;
    
        return 0;
    }
    

Conclusion

Strings in C++ are a powerful and versatile tool for handling textual data. From basic operations like concatenation and comparison to advanced manipulations such as changing case and finding substrings, strings play a crucial role in a C++ programmer's toolkit.

By understanding the various aspects of working with strings, including input and output, manipulation, and memory management, you are well-equipped to navigate the intricate landscape of string handling in C++.