C++ cstring

C-style string functions and character array operations

🔤 What is cstring?

The cstring library provides functions for working with C-style strings (character arrays). These functions handle null-terminated character arrays and provide basic string manipulation operations from the C language.


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

int main() {
    char str[] = "Hello World";
    cout << "Length: " << strlen(str) << endl;
    return 0;
}
                                    

Output:

Length: 11

cstring Functions

📏

strlen()

Calculate string length

char str[] = "Hello";
int len = strlen(str);  // len = 5
📋

strcpy()

Copy one string to another

char dest[20];
strcpy(dest, "Hello");  // Copy "Hello"

strcat()

Concatenate (join) strings

char str[20] = "Hello";
strcat(str, " World");  // "Hello World"
⚖️

strcmp()

Compare two strings

int result = strcmp("Apple", "Banana");
// result < 0 (Apple < Banana)

🔹 String Length and Copying

String Length and Copying operations manage C-style strings using functions like strlen() and strcpy() to determine size and duplicate content. For example, a string "Hello, C++ World!" has a length of 17 characters, and copying it creates an identical buffer. These operations are crucial for safe string manipulation, preventing buffer overflows and ensuring memory integrity. They form the basis for text processing, input validation, and data serialization in low-level programming, where direct memory management is required.

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

int main() {
    // Original string
    char source[] = "Hello, C++ World!";
    char destination[50];
    
    // Get string length
    int length = strlen(source);
    cout << "Source string: " << source << endl;
    cout << "Length: " << length << " characters" << endl;
    
    // Copy string
    strcpy(destination, source);
    cout << "Copied string: " << destination << endl;
    
    // Copy with limit (safer)
    char limited[10];
    strncpy(limited, source, 9);
    limited[9] = '\0';  // Ensure null termination
    cout << "Limited copy: " << limited << endl;
    
    // Copy part of string
    char partial[20];
    strcpy(partial, "Greetings");
    cout << "Partial string: " << partial << endl;
    
    return 0;
}

Output:

Source string: Hello, C++ World!
Length: 17 characters
Copied string: Hello, C++ World!
Limited copy: Hello, C+
Partial string: Greetings

🔹 String Concatenation

String Concatenation combines multiple C-style strings into one using functions like strcat(), enabling dynamic text assembly. Starting with "Hello" (length 5), adding " Alice" forms "Hello Alice" (length 11), and appending "!" finalizes the message. This process is essential for building user messages, log entries, or SQL queries, though it requires careful buffer sizing to avoid overflow. It highlights the importance of memory safety and efficient string handling in system-level applications.

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

int main() {
    // Create strings with enough space
    char greeting[50] = "Hello";
    char name[] = " Alice";
    char punctuation[] = "!";
    
    cout << "Initial greeting: " << greeting << endl;
    cout << "Length: " << strlen(greeting) << endl << endl;
    
    // Concatenate name
    strcat(greeting, name);
    cout << "After adding name: " << greeting << endl;
    cout << "Length: " << strlen(greeting) << endl;
    
    // Concatenate punctuation
    strcat(greeting, punctuation);
    cout << "Final message: " << greeting << endl;
    cout << "Final length: " << strlen(greeting) << endl;
    
    // Safe concatenation with limit
    char safe[20] = "Hi";
    strncat(safe, " there, friend!", 10);
    cout << "Safe concat: " << safe << endl;
    
    return 0;
}

Output:

Initial greeting: Hello
Length: 5

After adding name: Hello Alice
Length: 11
Final message: Hello Alice!
Final length: 12
Safe concat: Hi there, f

🔹 String Comparison

String comparison in C++ can be performed using relational operators (==, !=, <, etc.) or the .compare() member function. The operators provide a clear syntax for checking equality or lexicographical order (dictionary order), which is crucial for sorting alphabetically or validating passwords. The .compare() function offers more detailed results, returning zero for equality or a negative/positive number indicating order. Understanding comparison is vital for implementing search algorithms, sorting lists of names, managing access control, and organizing data in applications like phonebooks or file managers.

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

int main() {
    char str1[] = "Apple";
    char str2[] = "Banana";
    char str3[] = "Apple";
    char str4[] = "apple";  // Different case
    
    cout << "Comparing strings:" << endl;
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    cout << "str3: " << str3 << endl;
    cout << "str4: " << str4 << endl << endl;
    
    // Compare str1 and str2
    int result1 = strcmp(str1, str2);
    cout << "strcmp(str1, str2) = " << result1;
    if (result1 < 0) cout << " (str1 < str2)";
    else if (result1 > 0) cout << " (str1 > str2)";
    else cout << " (str1 == str2)";
    cout << endl;
    
    // Compare str1 and str3
    int result2 = strcmp(str1, str3);
    cout << "strcmp(str1, str3) = " << result2;
    if (result2 == 0) cout << " (strings are equal)";
    cout << endl;
    
    // Compare str1 and str4 (case sensitive)
    int result3 = strcmp(str1, str4);
    cout << "strcmp(str1, str4) = " << result3;
    if (result3 != 0) cout << " (different case matters)";
    cout << endl;
    
    // Compare first n characters
    int result4 = strncmp(str1, str4, 1);
    cout << "strncmp(str1, str4, 1) = " << result4 << " (first char only)" << endl;
    
    return 0;
}

Output:

Comparing strings:
str1: Apple
str2: Banana
str3: Apple
str4: apple

strcmp(str1, str2) = -1 (str1 < str2)
strcmp(str1, str3) = 0 (strings are equal)
strcmp(str1, str4) = -32 (different case matters)
strncmp(str1, str4, 1) = -32 (first char only)

🔹 String Searching

String Searching locates characters or substrings within C-style strings using functions like strchr(), strstr(), and strpbrk(). In a sentence like "The quick brown fox...", finding 'q' at position 4 or the substring "fox" at position 16 enables text analysis and parsing. These techniques are fundamental for log processing, data extraction, and pattern matching, allowing developers to efficiently navigate and manipulate string data in editors, interpreters, and network protocols.

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

int main() {
    char sentence[] = "The quick brown fox jumps over the lazy dog";
    
    cout << "Original sentence: " << sentence << endl;
    cout << "Length: " << strlen(sentence) << " characters" << endl << endl;
    
    // Find first occurrence of character
    char* found_char = strchr(sentence, 'q');
    if (found_char != nullptr) {
        cout << "Found 'q' at position: " << (found_char - sentence) << endl;
        cout << "Remaining string: " << found_char << endl;
    }
    
    // Find last occurrence of character
    char* last_char = strrchr(sentence, 'o');
    if (last_char != nullptr) {
        cout << "Last 'o' at position: " << (last_char - sentence) << endl;
    }
    
    // Find substring
    char* found_str = strstr(sentence, "fox");
    if (found_str != nullptr) {
        cout << "Found 'fox' at position: " << (found_str - sentence) << endl;
        cout << "From 'fox' onwards: " << found_str << endl;
    }
    
    // Search for characters in a set
    char* found_any = strpbrk(sentence, "xyz");
    if (found_any != nullptr) {
        cout << "Found character from 'xyz' set: " << *found_any << endl;
    }
    
    return 0;
}

Output:

Original sentence: The quick brown fox jumps over the lazy dog
Length: 43 characters

Found 'q' at position: 4
Remaining string: quick brown fox jumps over the lazy dog
Last 'o' at position: 41
Found 'fox' at position: 16
From 'fox' onwards: fox jumps over the lazy dog
Found character from 'xyz' set: x

🧠 Test Your Knowledge

Which function is used to find the length of a C-style string?