String Class and C-style string

In C++, handling strings is essential for many applications. Strings are sequences of characters, and manipulating them efficiently is crucial. C++ provides two main approaches for handling strings: the string class and C-style strings. This chapter explores both approaches, covering their usage, advantages, and drawbacks.

String Class

Basics of String Class

The string class in C++ is a part of the Standard Template Library (STL) and offers a modern and convenient way to work with strings. It provides various functionalities for string manipulation.

Example 1: Creating and Initializing a String

				
					#include <iostream>
#include <string>

using namespace std;

int main() {
    // Creating and initializing a string
    string myString = "Hello, World!";
    
    // Output the string
    cout << myString << endl;
    
    return 0;
}

				
			
				
					Hello, World!

				
			

Common Operations with String Class

Concatenation

You can concatenate strings using the + operator or the append() function.

				
					string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2; // Using the + operator
// Or
str1.append(" ");
str1.append(str2); // Using the append() function

				
			

Accessing Characters

You can access individual characters in a string using array-like indexing or the at() function.

				
					string myString = "Hello";
char ch = myString[0]; // Accessing first character
// Or
char ch2 = myString.at(1); // Accessing second character

				
			

Length of a String

You can get the length of a string using the length() or size() function.

				
					string myString = "Hello";
int length = myString.length();
// Or
int size = myString.size();

				
			

Common Operations

You can get the length of a string using the length() or size() function.

				
					#include <iostream>
#include <string>

using namespace std;

int main() {
    // Creating and initializing a string
    string myString = "Hello";
    cout << "Original String: " << myString << endl;

    // Concatenation
    string addition = " World";
    string concatenated = myString + addition;
    cout << "Concatenated String: " << concatenated << endl;

    // Accessing Characters
    char firstChar = concatenated[0];
    cout << "First Character: " << firstChar << endl;

    // Length of a String
    int length = concatenated.length();
    cout << "Length of String: " << length << endl;

    // Finding Substrings
    size_t pos = concatenated.find("World");
    if (pos != string::npos) {
        cout << "Substring 'World' found at position: " << pos << endl;
    } else {
        cout << "Substring not found" << endl;
    }

    // Extracting Substrings
    string extracted = concatenated.substr(6, 5);
    cout << "Extracted Substring: " << extracted << endl;

    // Modifying Substring
    extracted[0] = 'w';
    cout << "Modified Substring: " << extracted << endl;

    // Erasing Substring
    concatenated.erase(6, 5);
    cout << "String after erasing substring: " << concatenated << endl;

    // Inserting Substring
    concatenated.insert(6, " World");
    cout << "String after inserting substring: " << concatenated << endl;

    // Replacing Substring
    size_t replacePos = concatenated.find("World");
    concatenated.replace(replacePos, 5, "Universe");
    cout << "String after replacing substring: " << concatenated << endl;

    // Comparing Strings
    string compareString = "Hello Universe";
    if (concatenated == compareString) {
        cout << "Strings are equal" << endl;
    } else {
        cout << "Strings are not equal" << endl;
    }

    return 0;
}

				
			
				
					// output //
Original String: Hello
Concatenated String: Hello World
First Character: H
Length of String: 11
Substring 'World' found at position: 6
Extracted Substring: World
Modified Substring: world
String after erasing substring: Hello
String after inserting substring: Hello World
String after replacing substring: Hello Universe
Strings are equal

				
			

Explanation:

  • Modifying Substring: We change the first character of the extracted substring from ‘W’ to ‘w’.
  • Erasing Substring: We erase the substring ” World” from concatenated.
  • Inserting Substring: We insert the substring ” World” back into concatenated at position 6.
  • Replacing Substring: We replace the substring “World” with “Universe” in concatenated.
  • Comparing Strings: We compare concatenated with another string compareString and print whether they are equal or not. In this case, they are equal.

Advanced String Operations

Substring Extraction

You can extract a substring from a string using the substr() function.

Second Argument is the no. of characters you want to extract

				
					string myString = "Hello, World!";
string substring = myString.substr(7, 5); // Extract "World"

				
			

Finding Substrings

You can find the position of a substring within a string using the find() function.

This function will return the first index from where this substring is starting. 

				
					string myString = "Hello, World!";
size_t pos = myString.find("World"); // Returns 7

				
			

C-style Strings

Basics of C-style Strings

C-style strings are arrays of characters terminated by a null character ('\0'). They are a fundamental part of C programming but can be used in C++ as well.

Example 3: Initializing and Printing a C-style String

				
					#include <iostream>

using namespace std;

int main() {
    // Initializing a C-style string
    char myString[] = "Hello, World!";
    
    // Printing the string
    cout << myString << endl;
    
    return 0;
}

				
			
				
					Hello, World!

				
			

Common Operations with C-style Strings

Concatenation

Concatenating C-style strings involves using functions like strcpy() and strcat().

				
					#include <cstring>

char str1[20] = "Hello";
char str2[] = " World";
strcat(str1, str2); // Concatenates str2 to str1

				
			

Accessing Characters

Accessing characters in C-style strings is similar to arrays.

				
					char myString[] = "Hello";
char ch = myString[0]; // Accessing first character

				
			

Length of a C-style String

You can find the length of a C-style string using the strlen() function.

				
					char myString[] = "Hello";
int length = strlen(myString);

				
			

Common Operations with C-style Strings

				
					#include <iostream>
#include <cstring>

using namespace std;

int main() {
    // Initializing a C-style string
    char myString[20] = "Hello";
    char addition[] = " World";
    
    // Concatenation
    strcat(myString, addition);
    cout << "Concatenated String: " << myString << endl;
    
    // Accessing Characters
    char ch = myString[0];
    cout << "First Character: " << ch << endl;
    
    // Length of a C-style String
    int length = strlen(myString);
    cout << "Length of myString: " << length << endl;
    
    return 0;
}

				
			
				
					// output //
Concatenated String: Hello World
First Character: H
Length of myString: 11


				
			

Advantages and Disadvantages

String Class

Advantages:

  • Modern and convenient to use.
  • Handles memory management automatically.
  • Provides a wide range of functions for string manipulation.

Disadvantages:

  • Slightly slower due to dynamic memory allocation.
  • May consume more memory than C-style strings.

 

C-style Strings

Advantages:

  • Efficient and lightweight.
  • Faster performance due to static memory allocation.
  • Suitable for low-level programming.

Disadvantages:

  • Manual memory management required.
  • Lack of built-in functions for string manipulation.

In conclusion, both the string class and C-style strings offer different approaches to handle strings in C++. The string class provides modern functionalities and automatic memory management, making it suitable for most applications. On the other hand, C-style strings offer efficiency and are well-suited for low-level programming tasks. Understanding the strengths and weaknesses of each approach allows developers to choose the most appropriate method based on their specific requirements.Happy coding!❤️

Table of Contents