char site[7] = {'R', 'U', 'N', 'O', 'O', 'B', '\0'};
示例如上。
字符串常用函数:
号 | 函数 & 目的 |
---|---|
1 | strcpy(s1, s2); 复制字符串 s2 到字符串 s1。 |
2 | strcat(s1, s2); 连接字符串 s2 到字符串 s1 的末尾。连接字符串也可以用 + 号,例如: string str1 = "runoob"; string str2 = "google"; string str = str1 + str2; |
3 | strlen(s1); 返回字符串 s1 的长度。 |
4 | strcmp(s1, s2); 如果 s1 和 s2 是相同的,则返回 0;如果 s1<s2 则返回值小于 0;如果 s1>s2 则返回值大于 0。 |
5 | strchr(s1, ch); 返回一个指针,指向字符串 s1 中字符 ch 的第一次出现的位置。 |
6 | strstr(s1, s2); 返回一个指针,指向字符串 s1 中字符串 s2 的第一次出现的位置。 |
值得一提的是,str相关的函数会被警告,所以要在include语句导入头文件之前写入
#define _CRT_SECURE_NO_WARNINGS 1
另外,string类提供了一系列针对字符串的操作,比如:
- 1. append() -- 在字符串的末尾添加字符
- 2. find() -- 在字符串中查找字符串
- 4. insert() -- 插入字符
- 5. length() -- 返回字符串的长度
- 6. replace() -- 替换字符串
- 7. substr() -- 返回某个子字符串
#include <iostream>
#include <string>
using namespace std;
int main()
{
//定义一个string类对象
string http = "www.runoob.com";
//打印字符串长度
cout<<http.length()<<endl;
//拼接
http.append("/C++");
cout<<http<<endl; //打印结果为:www.runoob.com/C++
//删除
int pos = http.find("/C++"); //查找"C++"在字符串中的位置
cout<<pos<<endl;
http.replace(pos, 4, ""); //从位置pos开始,之后的4个字符替换为空,即删除
cout<<http<<endl;
//找子串runoob
int first = http.find_first_of("."); //从头开始寻找字符'.'的位置
int last = http.find_last_of("."); //从尾开始寻找字符'.'的位置
cout<<http.substr(first+1, last-first-1)<<endl; //提取"runoob"子串并打印
return 0;
}