较为常用的字符串操作函数
strncat函数 (链接字符)strncpy函数(拷贝字符)strncmp函数(比较)strchr函数 (字符串中找一个字符的位子)strstr函数(字符串中找字符串的位子)strtok函数(分割字符串)
代码及使用结果
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
int main() {
char s1[100] = "12345";
char s2[100] = "abcdefg";
char s3[100] = "ABCDE";
strncat_s(s1, s2, 3);//将s2前3个字符接到s1后面
cout <<"1."<< s1 << endl;
strncpy_s(s1,s3,3);
cout << "2." << s1 << endl;//将s3前3个字符赋值给s1
strncpy_s(s2, s3, 6);//将s3拷贝给s2
cout << "3." << s2 << endl;
cout << "4." << strncmp(s1, s3, 3) << endl;//比较s3与s1
char* p;
p = strchr(s1, 'B');//在s1中找b的位子
if (p)
cout << "5." << p - s1 << "," <<p <<","<< * p << endl;
else
cout <<"5." <<"not found" << endl;
p = strstr(s1, "BC");//在s1中找56a的位子
if (p)
cout << "6." <<p - s1 << "," << p << "," << *p << endl;
else
cout << "6." << "not found" << endl;
char a[] = "- hollow world.ok ,sir";
char *buf[20];
p = strtok_s (a, " ,-.",buf);//将句子的单词拆开
while (p != NULL) {
cout << p<<endl;
p = strtok_s(NULL, " ,.-",buf);
}
return 0;
结果
在vs里strncat函数 strncpy函数strncmp函数strchr函数 strstr函数strtok函数都需要改成strncat_s,strncpy_s,strncmp_s,strchr_s,strstr_s才能使用与修改前的函数使用方法一样
只有strtok_s与strtok使用方法不一样。strtok_s需要多一个数组去暂存拆分后的字符串。
计算机202 yjq