C++ Beginner

cpp_005_Introduction to Strings

codeaddict 2025. 1. 1. 16:20

C++ provides two primary ways to work with strings: C-style strings and the modern std::string class. This tutorial covers the key concepts, differences, and practical examples.


1. What Are Strings in C++?

A string is a sequence of characters. In C++, you can represent strings in two ways:

  1. C-style strings: Arrays of characters ending with a null character (\0).
  2. std::string: A part of the C++ Standard Library, providing an easier and safer way to work with strings.

2. C-Style Strings

C-style strings are simply arrays of characters terminated with a null character (\0). You need to manage their size manually.

Code Example:

#include <iostream>
#include <cstring> // For C-style string functions
using namespace std;

int main() {
    char cstr[] = "Hello, C-style strings!";
    cout << "C-Style String: " << cstr << endl;

    // String length using strlen()
    cout << "Length: " << strlen(cstr) << endl;

    // Concatenation using strcat()
    char greeting[50] = "Hello";
    strcat(greeting, ", World!");
    cout << "Concatenated String: " << greeting << endl;

    return 0;
}

Output:

C-Style String: Hello, C-style strings!
Length: 22
Concatenated String: Hello, World!

Key Points:

  • strlen(cstr): Returns the number of characters (excluding \0).
  • strcat(): Concatenates strings but requires enough space in the destination array.

3. std::string Class

std::string is a modern and more versatile way to work with strings. It automatically manages memory and provides many useful functions.


3.1 Declaring and Initializing Strings

If you don’t assign a value to a string, it’s blank (empty) by default.

Code Example:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Hello, ";
    string str2 = "std::string!";
    string emptyStr; // Default value is blank

    cout << "String 1: " << str1 << endl;
    cout << "String 2: " << str2 << endl;
    cout << "Empty String: '" << emptyStr << "'" << endl;

    return 0;
}

Output:

String 1: Hello, 
String 2: std::string!
Empty String: ''

3.2 Length of a String

You can use the .length() or .size() methods to find the length of a string.

Code Example:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello, World!";
    cout << "String: " << str << endl;
    cout << "Length: " << str.length() << endl;

    return 0;
}

Output:

String: Hello, World!
Length: 13

3.3 String Concatenation

Strings can be concatenated using the + operator.

Code Example:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "C++ ";
    string str2 = "is fun!";
    string result = str1 + str2;

    cout << "Concatenated String: " << result << endl;

    return 0;
}

Output:

Concatenated String: C++ is fun!

3.4 Modifying Strings

You can modify std::string easily with various operations.

Code Example:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello, C++!";
    str[7] = 'W'; // Replace 'C' with 'W'
    str.append(" Strings are cool!"); // Append to the string

    cout << "Modified String: " << str << endl;

    return 0;
}

Output:

Modified String: Hello, W++! Strings are cool!

3.5 Comparing Strings

You can compare two strings using relational operators.

Code Example:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Apple";
    string str2 = "Banana";

    if (str1 < str2) {
        cout << str1 << " comes before " << str2 << " alphabetically." << endl;
    } else {
        cout << str1 << " comes after " << str2 << " alphabetically." << endl;
    }

    return 0;
}

Output:

Apple comes before Banana alphabetically.

3.6 Finding Substrings

The find() method locates a substring within a string.

Code Example:

In this example, we are using the find() method to locate a substring within a string.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "C++ programming is fun!";
    size_t position = str.find("programming");

    if (position != string::npos) {
        cout << "'programming' found at position: " << position << endl;
    } else {
        cout << "'programming' not found!" << endl;
    }

    return 0;
}

Explanation

str.find("programming") searches for the first occurrence of the substring "programming" in the string str.

string::npos is a constant in the C++ Standard Library, representing an invalid position.

-The function returns the index (position) where the substring begins in the string, or it returns string::npos if the substring is not found.

If find() does not find the substring, it returns string::npos, which is typically a very large number (usually -1 as an unsigned integer).

position != string::npos checks if the substring was found. If it wasn't found, the value of position will be string::npos.

size_t position stores the result. The type size_t is an unsigned integer type, which is used for sizes and positions in C++.

If the substring is found, the position where it starts is printed. The position is 4 in this case because the substring "programming" begins at index 4 of the string "C++ programming is fun!".

Output:

'programming' found at position: 4

 


Conclusion

In this tutorial, we explored:

  • C-style strings and their limitations.
  • The versatile std::string class, including common methods like .length(), concatenation, and substring searching.
  • The fact that uninitialized std::string variables are blank by default.

For more advanced string manipulation functions, refer to the C++ String Documentation.