当前位置:首页C++程序设计 > 正文

C++中什么时候用字符数组字符串和string类举例

作者:野牛程序员:2023-06-14 12:24:54C++程序设计阅读 2747

当使用字符数组字符串时,以下是一些例子:

  1. 较低级别的字符串操作:

char str[10];
str[0] = 'H';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = '\\0'; // 字符串结尾的空字符
  1. C风格字符串:

char name[] = "John";
char greeting[20];
strcpy(greeting, "Hello, "); // 使用strcpy将一个字符串复制到另一个字符串
strcat(greeting, name); // 使用strcat将两个字符串连接起来
  1. 固定长度的字符串:

char postalCode[6]; // 固定长度的邮政编码字符串

当使用string类时,以下是一些例子:

  1. 高级字符串操作:

#include <string>
std::string str1 = "Hello";
std::string str2 = "World";
std::string result = str1 + ", " + str2; // 字符串拼接
int length = result.length(); // 获取字符串长度
std::string replaced = result.replace(6, 5, "Everyone"); // 替换子字符串
size_t found = result.find("World"); // 查找子字符串的位置
  1. 动态长度的字符串:

#include <string>
std::string dynamicStr;
dynamicStr = "This is a dynamic string.";
  1. STL容器和算法的使用:

#include <string>
#include <vector>
#include <algorithm>
std::vector<std::string> names;
names.push_back("Alice");
names.push_back("Bob");
names.push_back("Charlie");

std::sort(names.begin(), names.end()); // 对字符串进行排序
std::string foundName = *std::find(names.begin(), names.end(), "Bob"); // 在容器中查找特定字符串

这些例子只是展示了使用字符数组字符串和string类的一些常见情况,您可以根据具体的需求选择合适的方式来处理字符串。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击