目录
函数对比
1. 字符串连接
- c++ string
string str1 = "Hello";
string str2 = ", World!";
string result = str1 + str2;
- c++ char array
char arr1[] = "Hello";
char arr2[] = ", World!";
char result[20];
strcpy(result, arr1);
strcat(result, arr2);
- python
str1 = "Hello"
str2 = ", World!"
result = str1 + str2
- python
strings = ["Hello", ", World!"]
result = "".join(strings)
2. 查找子串
- c++ string
string str = "Hello, World!";
int pos = str.find("World");
if (pos != string::npos) {
cout << "子串在字符串中的位置:" << pos << endl;
}
else
std::cout << "未找到子串" << std::endl;
- c++ char array
char arr[] = "Hello, World!";
char* substr = strstr(arr, "World");
if (substr != nullptr) {
cout << "子串在字符串中的位置:" << substr - arr << std::endl;
}
else
cout << "未找到子串" << endl;
- python
text = "Hello, World!"
pos = text.find("World")
if pos != -1:
print("子串在字符串中的位置:", pos)
else:
print("未找到子串")
3. 替换子串
- c++ string
string str = "Hello, World!";
int pos = str.find("World");
if (pos != npos) {
str.replace(pos, 5, "Universe");
cout << "替换后的字符串:" << str << endl;
}
else
cout << "未找到子串" << endl;
- c++ char array(无内置函数)
char arr[] = "Hello, World!";
const char* search = "World";
const char* replacement = "Universe";
char* start = strstr(original, search);
if (start != nullptr) {
int searchLen = strlen(search);
int replacementLen = strlen(replacement);
int tailLen = strlen(start + searchLen);
// 计算新的字符串长度
int newLen = strlen(original) - searchLen + replacementLen;
// 创建一个新的字符数组来存储替换后的字符串
char* newString = new char[newLen + 1];
// 复制原始字符串的前半部分
strncpy(newString, original, start - original);
// 复制替换的字符串
strncpy(newString + (start - original), replacement, replacementLen);
// 复制原始字符串的后半部分
strncpy(newString + (start - original) + replacementLen, start + searchLen, tailLen);
// 在新字符串的末尾添加 null 终止符
newString[newLen] = '\0';
// 将新字符串复制回原始字符数组
strcpy(original, newString);
// 释放动态分配的内存
delete[] newString;
}
cout << "替换后的字符串:" << arr << endl;
text = "Hello, World!"
new_text = text.replace("World", "Universe")
print("替换后的字符串:", new_text)
4. 字符串长度
- c++ string
int length1 = arr1.length();
int length2 = arr2.size();
- c++ char array
int length = strlen(arr);
- python
length = len(arr);
部分字符数组函数(c++ char array)
在 C++ 中,strcpy
、strncpy
和 strcat
是字符串处理中常用的字符数组函数,用于复制和连接字符串。以下是它们的基本用法:
1. strcpy(字符串复制)
char source[] = "Hello, World!";
char destination[20]; // 目标数组的大小要足够大
strcpy(destination, source);
cout << "复制后的字符串:" << destination << endl;
2. strncpy(指定长度的字符串复制)
char source[] = "Hello, World!";
char destination[20]; // 目标数组的大小要足够大
// 使用 strncpy 复制字符串,限制复制的字符数
strncpy(destination, source, sizeof(destination) - 1);
destination[sizeof(destination) - 1] = '\0'; // 手动添加 null 终止符
cout << "复制后的字符串:" << destination << endl;
3. strcat(字符串连接)
char str1[20] = "Hello, ";
char str2[] = "World!";
// 使用 strcat 连接字符串
strcat(str1, str2);
// 输出连接后的字符串
cout << "连接后的字符串:" << str1 << endl;