在国外做电商网站,中国网站建设银行-个人客户,淘宝网的网站建设,云南网站开发费用一.string类#x1f357; C支持C风格的字符串#xff0c;另外还提供了一种 字符串数据类型#xff1a; string是定义在头文件string中的类#xff0c;使用前需要包含头文件string。 #includestring C语言中的字符串需要引用头文件#includestring.h #includ… 一.string类 C支持C风格的字符串另外还提供了一种 字符串数据类型 string是定义在头文件string中的类使用前需要包含头文件string。 #includestring C语言中的字符串需要引用头文件#includestring.h #includestring.h 值得注意的是在c中头文件中都没有.h 二.使用 1.赋值的三种方法 //C风格
int main()
{string s1;//第一种方式,字符串赋值s1 hello c;string s2 今天,好好学习了吗?; //第二种方式,字符串初始化string s3{ 你学废了吗?}; //第三种方式 ,用字符串构造stringcout s1 endl;cout s2 endl;cout s3 endl;return 0;
} 第一种方式先定义了string变量s1再为string变量s1赋值第二种方式直接使用“ ”为string变量s2赋值第三种方式在定义string变量时将初始值放在“{ }”运算符中使用“{ }”运算符中的字符串为变量初始化 2,关于字符串的各种操作 1.访问字符串中的字符 string类重载了“[]”运算符可以通过索引方式访问和操作字符串中指定位置的字符。如下所示 //string类重载了“[]”运算符可以通过索引方式访问和操作字符串中指定位置的字符。如下所示
//C
int main()
{string s hello,C;cout s endl;s[7] P;//通过下标访问第七个元素s[8] P;cout s endl; //hello,Cppreturn 0;
}//C语言
int main()
{char s[] hello,C;printf(%s\n, s);s[7] p;s[8] p;printf(%s\n, s);return 0;
} 2.字符串连接 在C语言中连接两个字符串要调用strcat()函数还要考虑内存溢出情况。在C中string重载了“ ”运算符可以使用“ ”运算符连接两个string类型的字符串如下所示 //C写法
int main()
{string s1, s2;s1 我在学习;s2 C;cout s1 s2 endl; //我在学习Creturn 0;
}//C写法
int main()
{char s1[15] 我在学习;char s2[15] C;strcat(s1, s2);printf(%s, s1);return 0;
}3.字符串的比较(注意比较的不是长度而是字母的大小) 在C语言中比较两个字符串是否相等需要调用strcmp()函数而在C中可以直接使用的“ ”, “ ”, “ ”等运算符比较两个string字符串。如下所示 //C
int main()
{string s1, s2;s1 hello;s2 world;//比较两个字符串内容是否相同 if (s1 s2)cout 字符串s1大于s2 endl;else if (s1 s2)cout 字符串s2大于s1 endl;elsecout 字符串s1与s2相等 endl;
}//C语言
int main()
{char s1[10] hello;char s2[10] world;//比较两个字符串内容是否相同 if (strcmp(s1 ,s2)0)printf(字符串s1大于s2);else if (strcmp(s1 , s2))printf(字符串s2大于s1);elseprintf(字符串s1与s2相等);
}4.字符串的长度计算 string类提供的length()函数用于获取字符串长度。length()函数类似于C语言中的strlen()函数。调用length()函数获取字符串长度, 如下所示 int main()
{string s hello C;cout 长度: s.length() endl;//9return 0;
} 5.字符串交换 string类提供了成员函数swap()用于交换两个字符串的值示例代码如下所示 int main()
{string s1 hello;string s2 world;cout 交换前 s1 s2 endl;//s1.swap(s2); //交换s1与s2的内容swap(s1, s2);cout 交换后 s1 s2 endl;return 0;
} 6.使用 getline() 函数来获取 string 输入 int main()
{string s;getline(cin, s);cout s;return 0;
}7.erase() 进行元素删除操作 int main()
{string str(Hello,World!!);str.erase(5, 6); // 下标为0开始 删除从索引位置 5 (包括第五个字符)开始的 6 个字符cout str为 str endl; //Hello!!return 0;
} 本篇完.