The third day of learning C++ in fourteen days (arrays and strings)

Insert image description here

1. Definition and initialization of array

An array is a collection of elements of the same data type that are stored in consecutive memory locations in a certain order. The size of an array is fixed when it is created and cannot be changed at runtime.

In C++, the definition and declaration of arrays are very simple. Define an array:

数据类型 数组名[数组大小];

The data type can be integers, floating point numbers, characters, etc. The array name is the name you give the array, and the array size indicates the number of elements the array can hold. Example:

int numbers[5];          // 整数数组,包含5个元素
double temperatures[7];  // 浮点数数组,包含7个元素
char vowels[5];          // 字符数组,包含5个元素

Initialization of the array. Arrays can be initialized when declared or assigned later. Static initialization provides an initial value at the time of declaration, and dynamic initialization uses an assignment statement to assign an initial value after the declaration.

Static initialization:

int numbers[5] = {
    
    1, 2, 3, 4, 5}; // 静态初始化,包含5个整数

Dynamic initialization:

double temperatures[7];  // 声明数组
temperatures[0] = 98.6;  // 动态初始化第一个元素
temperatures[1] = 95.5;  // 动态初始化第二个元素
// 以此类推...

2. Basic operations on arrays

Accessing array elements: To access an element in an array, use the array name followed by square brackets that contain the index of the element (starting from 0). Access the first element in an array:

int numbers[5] = {
    
    1, 2, 3, 4, 5};
int firstNumber = numbers[0]; // 访问第一个元素

Modify an array element: Modify an element in the array, using the same index to specify the element to be modified, and assign a new value to it. Modify the third element in the array:

int numbers[5] = {
    
    1, 2, 3, 4, 5};
numbers[2] = 100; // 修改第三个元素的值为100

Get the length of an array: In C++, getting the length of an array can sizeofbe achieved using operators. Get numbersthe length of the above array:

int length = sizeof(numbers) / sizeof(numbers[0]);

Returns the number of elements in an array, controlling array access during loops and other operations.

Traversing an array: Traversing an array means accessing each element of the array. This is done through loops, most commonly using forloops. Example of looping through an array and printing each element:

int numbers[5] = {
    
    1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
    
    
    cout << numbers[i] << " "; // 打印每个元素
}

3. String processing

Introducing the concept of string: A string is a sequence of characters representing text data. In C++, there are two main ways of representing strings: C-style strings and C++ string classes.

C-style strings: C-style strings are actually arrays of characters, '\0'terminated by the null character. For example:

char greeting[] = "Hello, World!";

C-style strings require manual handling of string length and memory allocation.

C++ String Class: C++ provides a std::stringstring class called C++, which is a modern replacement for C-style strings. Using the string class, you can easily handle strings without worrying about memory management and length issues.

#include <string>
std::string greeting = "Hello, World!";

Basic string operations: Whether it is C-style string or C++ string class, basic string operations are supported, such as concatenation, substring search, comparison, etc. Example:

  • Concatenate strings:
std::string firstName = "John";
std::string lastName = "Doe";
std::string fullName = firstName + " " + lastName;
  • Find a substring:
std::string sentence = "This is a sample sentence.";
size_t found = sentence.find("sample");
if (found != std::string::npos) {
    
    
    std::cout << "Found 'sample' at position " << found << std::endl;
}
  • Compare strings:
std::string str1 = "apple";
std::string str2 = "banana";
int result = str1.compare(str2);
if (result == 0) {
    
    
    std::cout << "Strings are equal." << std::endl;
} else if (result < 0) {
    
    
    std::cout << "str1 is less than str2." << std::endl;
} else {
    
    
    std::cout << "str1 is greater than str2." << std::endl;
}

4. C-style strings and C++ string classes

Compare C-style strings and C++ string classes:

  • C-style string (character array):
    • Represented using a character array, '\0'terminated by the null character ( ).
    • Requires manual management of memory and length.
    • The operation is cumbersome and can easily cause cross-border and memory leaks.
char greeting[20] = "Hello, World!";
  • C++ string class ( std::string):
    • Use classes provided by the modern C++ standard library std::string.
    • Automatically manage memory, no need to worry about memory allocation and release.
    • Provides rich string operation methods, which are safer and more efficient.
#include <string>
std::string greeting = "Hello, World!";

Common operations on C++ string classes:

  • Concatenate strings:
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string greeting = str1 + str2;  // "Hello, World!"
  • Find a substring:
std::string sentence = "This is a sample sentence.";
size_t found = sentence.find("sample");
if (found != std::string::npos) {
    
    
    std::cout << "Found 'sample' at position " << found << std::endl;
}
  • Replace substring:
std::string sentence = "The quick brown fox jumps over the lazy dog.";
sentence.replace(10, 5, "red");  // Replace "brown" with "red"

5. Examples and Exercises

Example 1: Use an array to store a set of numbers and calculate their average.

#include <iostream>

int main() {
    
    
    int numbers[] = {
    
    10, 20, 30, 40, 50};
    int sum = 0;

    for (int i = 0; i < 5; i++) {
    
    
        sum += numbers[i];
    }

    double average = static_cast<double>(sum) / 5;
    std::cout << "Average: " << average << std::endl;

    return 0;
}

operation result:
Insert image description here

Example 2: Use a string to process the name entered by the user and output a welcome message.

#include <iostream>
#include <string>

int main() {
    
    
    std::string name;
    std::cout << "Enter your name: ";
    std::cin >> name;
    std::cout << "Welcome, " << name << "!" << std::endl;

    return 0;
}

operation result:
Insert image description here

Practice questions:

  1. Create an array of integers to store the test scores of a group of students and calculate the average score.

  2. Write a program that asks the user to enter a sentence and then counts the number of words in the sentence.

  3. Using the C++ string class, write a program that concatenates two strings together and outputs the result.

  4. Create a character array to store one of your favorite quotes, and write a program to replace one word in it with another.

Question 1: Create an integer array to store the test scores of a group of students and calculate the average score.

#include <iostream>

int main() {
    
    
    const int numStudents = 5; // 假设有5名学生
    int scores[numStudents];
    int sum = 0;

    // 输入学生的成绩
    for (int i = 0; i < numStudents; i++) {
    
    
        std::cout << "输入第 " << i + 1 << " 名学生的成绩:";
        std::cin >> scores[i];
        sum += scores[i];
    }

    double average = static_cast<double>(sum) / numStudents;
    std::cout << "平均分:" << average << std::endl;

    return 0;
}

operation result:Insert image description here

Question 2: Write a program that requires the user to enter a sentence and then counts the number of words in the sentence.

#include <iostream>
#include <string>

int main() {
    
    
    std::string sentence;
    int wordCount = 0;

    std::cout << "请输入一个句子:";
    std::getline(std::cin, sentence);

    // 通过空格切分句子并统计单词数
    for (char c : sentence) {
    
    
        if (c == ' ') {
    
    
            wordCount++;
        }
    }

    // 最后一个单词后没有空格,所以需要额外加一
    wordCount++;

    std::cout << "单词数:" << wordCount << std::endl;

    return 0;
}

operation result:Insert image description here

Question 3: Using the C++ string class, write a program to splice two strings together and output the result.

#include <iostream>
#include <string>

int main() {
    
    
    std::string str1 = "Hello, ";
    std::string str2 = "World!";
    std::string result = str1 + str2;

    std::cout << result << std::endl;

    return 0;
}

operation result:Insert image description here

Question 4: Create a character array to store one of your favorite quotes, and write a program to replace one word in it with another word.

#include <iostream>
#include <cstring>

int main() {
    
    
    char quote[] = "生活不止眼前的苟且,还有诗和远方。";
    const char* wordToReplace = "苟且";
    const char* replacement = "快乐";

    // 查找目标单词的位置
    char* found = std::strstr(quote, wordToReplace);

    if (found) {
    
    
        // 找到目标单词,进行替换
        int position = found - quote;
        std::strcpy(quote + position, replacement);
    }

    std::cout << quote << std::endl;

    return 0;
}

operation result:
Insert image description here

Guess you like

Origin blog.csdn.net/m0_53918860/article/details/133529237