Using Strings in Arrays with C++

Basic Usage of String Arrays

In C++, we can use character arrays to store and manipulate strings. Here are two of the most common methods to initialize string arrays.

Method 1: Initialize with String Literals

#include <iostream>
#include <cstring> // Provides string functions like strlen()

int main() {
    // Method 1: Initialize with string literals
    const int Size = 20;
    char name1[Size] = "C++ Programmer"; // Automatically adds '\0'
    
    // Display content and length
    std::cout << "Name: " << name1 << std::endl;
    std::cout << "Length: " << strlen(name1) << " characters\n";
    
    return 0;
}

Method 2: Read Strings from Input

#include <iostream>
#include <cstring>

int main() {
    const int Size = 20;
    char name2[Size];
    
    // Method 2: Read from keyboard input
    std::cout << "Enter your name (max " << Size-1 << " chars): ";
    std::cin.getline(name2, Size); // Safer input method
    
    std::cout << "Hello, " << name2 << "!\n";
    std::cout << "Length: " << strlen(name2) << " characters\n";
    
    return 0;
}

Common Operations on String Arrays

Example 1: Copying and Concatenating Strings

#include <iostream>
#include <cstring>

void stringArrayOperations() {
    const int Size = 30;
    char str1[Size] = "Hello";
    char str2[Size] = "World";
    char result[Size];
    
    // String copy
    strcpy(result, str1); // result = "Hello"
    std::cout << "After copy: " << result << std::endl;
    
    // String concatenation
    strcat(result, " ");  // result = "Hello "
    strcat(result, str2); // result = "Hello World"
    std::cout << "After concatenation: " << result << std::endl;
    
    // Safe version (to prevent buffer overflow)
    strncpy(result, "New Content", Size-1);
    result[Size-1] = '\0'; // Ensure termination
    std::cout << "After safe copy: " << result << std::endl;
}

Example 2: Comparing and Searching Strings

#include <iostream>
#include <cstring>

void stringComparison() {
    char password[20] = "secret123";
    char input[20];
    
    std::cout << "Enter password: ";
    std::cin.getline(input, sizeof(input));
    
    // String comparison
    if (strcmp(password, input) == 0) {
        std::cout << "Access granted!\n";
    } else {
        std::cout << "Access denied!\n";
    }
    
    // String search
    char sentence[] = "The quick brown fox jumps over the lazy dog";
    char* found = strstr(sentence, "fox");
    
    if (found) {
        std::cout << "'fox' found at position: " << (found - sentence) << std::endl;
    }
}

Two-Dimensional Character Arrays (String Arrays)

Example 3: Storing Multiple Strings

#include <iostream>
#include <cstring>

void multiStringArray() {
    // Store 5 strings, each with a maximum of 19 characters + '\0'
    const int Rows = 5;
    const int Cols = 20;
    char languages[Rows][Cols] = {
        "C++",
        "Python",
        "Java",
        "JavaScript",
        "Go"
    };
    
    // Display all languages
    std::cout << "Programming Languages:\n";
    for (int i = 0; i < Rows; ++i) {
        std::cout << i+1 << ". " << languages[i] << " (length: " 
                  << strlen(languages[i]) << ")\n";
    }
    
    // Add new language (must ensure enough space)
    strncpy(languages[1], "TypeScript", Cols-1);
    languages[1][Cols-1] = '\0';
    std::cout << "\nAfter modification:\n" << languages[1] << std::endl;
}

Files and String Arrays

Example 4: Reading from a File into a String Array

#include <iostream>
#include <fstream>
#include <cstring>

void readFromFile() {
    const int MaxLines = 10;
    const int MaxLength = 100;
    char lines[MaxLines][MaxLength];
    int lineCount = 0;
    
    std::ifstream file("data.txt");
    if (!file) {
        std::cerr << "Cannot open file!\n";
        return;
    }
    
    // Read file content into array
    while (lineCount < MaxLines && file.getline(lines[lineCount], MaxLength)) {
        lineCount++;
    }
    
    // Display read content
    std::cout << "File content (" << lineCount << " lines):\n";
    for (int i = 0; i < lineCount; ++i) {
        std::cout << i+1 << ": " << lines[i] << std::endl;
    }
}

Safety Considerations

Example 5: Safe String Input Handling

#include <iostream>
#include <cstring>

void safeInputHandling() {
    const int BufSize = 10;
    char buffer[BufSize];
    
    std::cout << "Enter a string (max " << BufSize-1 << " chars): ";
    
    // Unsafe approach (may cause buffer overflow)
    // std::cin >> buffer; // Dangerous!
    
    // Safe approach 1: use getline to limit length
    std::cin.getline(buffer, BufSize);
    std::cout << "You entered: " << buffer << std::endl;
    
    // Clear input buffer
    if (strlen(buffer) == BufSize-1) {
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    
    // Safe approach 2: use string class
    std::string safeStr;
    std::cout << "Enter a long string: ";
    std::getline(std::cin, safeStr); // No length limit
    std::cout << "Safe string: " << safeStr << std::endl;
}

Performance Optimization Tips

Example 6: Efficiently Handling Large String Arrays

#include <iostream>
#include <cstring>

void processLargeStringArray() {
    const int Count = 1000;
    const int Size = 100;
    static char bigArray[Count][Size]; // Static storage duration
    
    // Bulk initialization
    for (int i = 0; i < Count; ++i) {
        snprintf(bigArray[i], Size, "String %d", i);
    }
    
    // Efficient search (example: find specific string)
    const char* searchFor = "String 500";
    for (int i = 0; i < Count; ++i) {
        if (strcmp(bigArray[i], searchFor) == 0) {
            std::cout << "Found at index: " << i << std::endl;
            break;
        }
    }
    
    // Bulk processing
    int totalLength = 0;
    for (int i = 0; i < Count; ++i) {
        totalLength += strlen(bigArray[i]);
    }
    std::cout << "Total characters: " << totalLength << std::endl;
}

Practical Application: Simple Login System

#include <iostream>
#include <cstring>

void simpleLoginSystem() {
    const int MaxUsers = 10;
    const int NameLength = 20;
    const int PassLength = 20;
    
    char usernames[MaxUsers][NameLength] = {"admin", "user1", "guest"};
    char passwords[MaxUsers][PassLength] = {"123456", "password", "guest"};
    int userCount = 3;
    
    char inputUser[NameLength];
    char inputPass[PassLength];
    
    std::cout << "Username: ";
    std::cin.getline(inputUser, NameLength);
    
    std::cout << "Password: ";
    std::cin.getline(inputPass, PassLength);
    
    // Validate login
    bool authenticated = false;
    for (int i = 0; i < userCount; ++i) {
        if (strcmp(inputUser, usernames[i]) == 0 && 
            strcmp(inputPass, passwords[i]) == 0) {
            authenticated = true;
            break;
        }
    }
    
    if (authenticated) {
        std::cout << "Login successful!\n";
    } else {
        std::cout << "Invalid username or password!\n";
    }
}

Modern C++ Alternatives

While C-style string arrays are still useful, in modern C++ we recommend using:

#include <iostream>
#include <vector>
#include <string>

void modernAlternative() {
    // Using vector and string is safer and more convenient
    std::vector<std::string> languages = {
        "C++", "Python", "Java", "JavaScript", "Go"
    };
    
    // Add new element
    languages.push_back("Rust");
    
    // Iterate and output
    for (const auto& lang : languages) {
        std::cout << lang << " (length: " << lang.length() << ")\n";
    }
    
    // Read from file
    std::ifstream file("data.txt");
    std::vector<std::string> lines;
    std::string line;
    
    while (std::getline(file, line)) {
        lines.push_back(line);
    }
}

Key Takeaways

  1. Always reserve space: Leave space for the ‘\0’ terminator
  2. Use safe functions: Prefer using <span>strncpy</span> over <span>strcpy</span>, use <span>getline</span> over <span>cin >></span>
  3. Check boundaries: Ensure not to exceed array boundaries
  4. Consider encoding: Be mindful of character encoding when handling multilingual text
  5. Modern alternatives: Use <span>std::string</span> and <span>std::vector</span> where possible

By properly using string arrays, we can efficiently handle text data in C++, while being mindful of safety and boundary conditions to avoid common issues like buffer overflows.

Leave a Comment