C++之数组和字符串

在C++中,数组和字符串是存储和操作数据的两种基本方式。下面我将分别介绍数组和字符串的基本概念和使用。

数组

一维数组

一维数组是最简单的数组形式,它存储相同类型的元素。声明一维数组的语法如下:

复制代码
type arrayName[arraySize];

例如,声明一个包含10个整数的数组:

复制代码
int numbers[10];
多维数组

多维数组可以看作是数组的数组。二维数组的声明语法如下:

复制代码
type arrayName[rowSize][columnSize];

例如,声明一个2x3的整数数组:

复制代码
int matrix[2][3];
动态数组(使用new和delete)

动态数组在运行时分配大小,使用newdelete操作符。例如,创建一个动态数组:

复制代码
int* dynamicArray = new int[arraySize];

使用完毕后,需要使用delete[]来释放内存:

复制代码
delete[] dynamicArray;

字符串

字符串常量

字符串常量是字符数组的只读版本,通常用双引号括起来。例如:

复制代码
const char str[] = "Hello, World!";
字符串处理函数

C语言风格字符串提供了一些基本的字符串处理函数,如strlen(计算字符串长度)、strcpy(复制字符串)、strcat(连接字符串)、strcmp(比较字符串)等。例如:

复制代码
#include <cstring>

char str1[] = "Hello";
char str2[10];

// 复制str1到str2
strcpy(str2, str1);

// 连接" World"到str2
strcat(str2, " World");

// 比较str1和str2
if (strcmp(str1, str2) != 0) {
    // 字符串不相等
}
std::string 类的使用

C++提供了std::string类,它是一个可变长度的字符串类,提供了丰富的成员函数来处理字符串。使用std::string需要包含头文件<string>。以下是一些基本操作:

复制代码
#include <string>
#include <iostream>

int main() {
    std::string str1 = "Hello";
    std::string str2 = "World";

    // 连接字符串
    str1 += ", " + str2;

    // 获取字符串长度
    std::cout << "Length of str1: " << str1.length() << std::endl;

    // 比较字符串
    if (str1 == str2) {
        std::cout << "Strings are equal." << std::endl;
    } else {
        std::cout << "Strings are not equal." << std::endl;
    }

    return 0;
}

std::string类还提供了其他功能,如查找子串、替换字符、插入和删除字符等。

相关推荐
im_AMBER21 分钟前
Leetcode 102 反转链表
数据结构·c++·学习·算法·leetcode·链表
今儿敲了吗42 分钟前
01|多项式输出
c++·笔记·算法
程序员Jared44 分钟前
C++11—mutex
c++
朔北之忘 Clancy1 小时前
2025 年 9 月青少年软编等考 C 语言一级真题解析
c语言·开发语言·c++·学习·数学·青少年编程·题解
Xの哲學1 小时前
深入剖析Linux文件系统数据结构实现机制
linux·运维·网络·数据结构·算法
量子炒饭大师1 小时前
【C++入门】Cyber底码作用域的隔离协议——【C++命名空间】(using namespace std的原理)
开发语言·c++·dubbo
AlenTech1 小时前
200. 岛屿数量 - 力扣(LeetCode)
算法·leetcode·职场和发展
C雨后彩虹1 小时前
竖直四子棋
java·数据结构·算法·华为·面试
REDcker1 小时前
RTCP 刀尖点跟随技术详解
c++·机器人·操作系统·嵌入式·c·数控·机床
楚Y6同学1 小时前
基于 Haversine 公式实现【经纬度坐标点】球面距离计算(C++/Qt 实现)
开发语言·c++·qt·经纬度距离计算