1.strlen():计算字符串的长度
2.strcpy():字符串复制
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[] = "Hello, world!";
char d[20]; // 目标数组必须足够大
strcpy(d, s); // 将s复制到d
cout << d << endl;
return 0;
}
3.strcat():字符串拼接
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[20] = "Hello";
char d[]=", world!";
strcat(s,d); // 将d拼接到s后面
cout <<s<< endl;
return 0;
}
4.strlen():字符串长度
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char text[] = "Hello, world!";
size_t length = strlen(text); // 计算字符串长度
cout<<length<<endl;
return 0;
}
(size_t
是一个无符号的整数类型,常用于表示内存大小和数组索引)
5.strcmp():字符串的比较
用于比较两个C语言风格的字符串,返回值:
=0:两个字符串相等
<0:第一个字符串小于第二个
>0:第一个字符串大于第二个
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[] = "Hello";
char str2[] = "World";
if (strcmp(str1, str2) == 0) {
cout << "equal" <<endl;
} else {
cout << "not equal" <<endl;
}
return 0;
}
6.strchr():在字符串中查找某个字符的首次出现的位置
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char text[] = "Hello, world!";
char* found = strchr(text, 'w'); // 查找字符 'w'
if (found) {
cout<<found - text<<endl;
} else {
cout << "not found" <<endl;
}
return 0;
}
7.strstr():在字符串中查找子字符串首次出现的位置
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char text[] = "Hello, world!";
char * found = strstr(text, "world"); // 查找字符 'w'
if (found) {
cout<<found - text<<endl;
} else {
cout << "not found" <<endl;
}
return 0;
}
8.algorithm和string中find的区别:
find返回的是一个迭代器,可以用于各种容器类型,不是专门用于字符串的查找,而是用于查找任意类型的元素
#include <iostream>
#include <vector>
#include <algorithm> // 包含 std::find()
using namespace std;
int main() {
vector<int> numbers = {10, 20, 30, 40, 50};
// 使用find 查找值为 30 的元素
auto it =find(numbers.begin(), numbers.end(), 30);
if (it != numbers.end()) {
cout<< distance(numbers.begin(), it) <<endl;
} else {
cout << "30 not found" <<endl;
}
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
// 使用find 查找值为 4 的元素
auto i = find(arr, arr + n, 4);
if (i != arr + n) {
cout <<(i - arr) <<endl;
} else {
cout << "4 not found" << endl;
}
return 0;
}
distance用于计算两个迭代器之间的距离,在头文件<iterator>中
string::find()
专门用于字符串查找,返回子字符串或字符的位置。