C++基础:字符串

字符串

字符串是一种非常常见的数据类型,用于存储和操作文本数据。C++提供了多种方式来表示字符串,其中最常用的是使用std::string类。以下是关于C++字符串的一些基本信息和操作示例:

字符 : ’ '(单引号是一个字符,如果要赋值成数组后面要加上 /0 其中 /0 为空字符),

字符串: " "(双引号是一个字符串是默认带 /0 的):其实双引号代表着的是一个地址。

strlen:字符串的有效长度,这里是指,,如果设置为15个长度数组,但是只用到了4个有效数组这个函数就只返回4个字节

 strlen(字符串变量)

字符串几种类型

字符串复制:strcpy(变量1,变量2):对变量复制

字符串的拼接:strcat():字符串的拼接

1:字符串包含头文件:要使用string类,您需要包含头文件。

#include 

2:创建字符串变量:您可以使用string类创建字符串变量。

std::string myString = "Hello, World!";

3:字符串输入和输出:您可以使用cin来输入字符串,并使用cout来输出字符串。

#include 
#include 

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

4:字符串拼接:您可以使用+运算符将两个字符串拼接在一起。

std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string result = str1 + str2;

struct inflatable:结构体

struct  inflatable 
{
	char name[20];
	float volume;
	double price;
}

字符串例子

#include 
#include 

int main() {
    // 使用std::string来创建字符串
    std::string str1 = "Hello, ";
    std::string str2 = "world!";
    
    // 字符串连接
    std::string result = str1 + str2;
    
    // 打印结果
    std::cout << result << std::endl;
    
    // 获取字符串长度
    int length = result.length();
    std::cout << "Length of the string: " << length << std::endl;
    
    // 访问字符串中的字符
    char firstChar = result[0];
    std::cout << "First character: " << firstChar << std::endl;
    
    // 修改字符串中的字符
    result[7] = 'W'; // 将小写的 'w' 修改为大写 'W'
    std::cout << result << std::endl;
    
    // 使用字符串的成员函数进行操作
    std::string substring = result.substr(0, 5); // 提取子串
    std::cout << "Substring: " << substring << std::endl;
    
    // 查找子字符串
    size_t found = result.find("world");
    if (found != std::string::npos) {
        std::cout << "Substring found at index: " << found << std::endl;
    } else {
        std::cout << "Substring not found" << std::endl;
    }
    
    return 0;
}

创建枚举量,枚举赋值必须是整型,int或long或long long

enum spectrum{red,orange,yellow,green,blue,violet,indigo,ultraviolet};
括号内的是枚举量
spectrum :枚举类
spectrum  band;  :通过枚举类创建枚举变量

枚举的取值范围如下,首先,
要找到上限,需要知道枚举的最大值,找到小于这个最大值的,最小的2的幂,将它减去1,得到的便是取值范围的上限。
要找到下限:需要知道枚举量的最小值,如果它不小于0,则取值范围的下限为0,否则采用与寻找上限方式相同的方式,但加上负号,列如,如果最小的枚举量为-6,而比他小的,最大的2的幂是-8,因此下限为-7
上限:
C++基础:字符串_第1张图片下限:
C++基础:字符串_第2张图片

你可能感兴趣的:(#,C++基础,c++,开发语言)