C++ string的详细总结

文章目录


一、string 的基础知识

1.string的基本概念和构造

#include <iostream>
using namespace std;
#include <string>

// string 构造函数

/*
string()                      //默认构造
string(const char *s)     //使用字符串s初始化
string(const string &str) //拷贝构造
string(int n, char c)     //使用n个字符c初始化
*/

void test() {
  string s1; //默认构造

  const char *str = "hello word"; // c语言风格的字符串
  string s2(str);
  cout << "s2 = " << s2 << endl;

  string s3(s2);  //拷贝构造
  cout << "s3 = " << s3 << endl;

  string s4(10, 'a');//使用n个字符c初始化
  cout << "s4 = " << s4 << endl;
}

int main() {
  test();
  return 0;
}

注意:string的多种构造方式没有可比性,灵活使用即可。

2.string 赋值操作

#include <iostream>
using namespace std;
#include <string>

// string 的赋值操作

void test() {
  string str1;
  str1 = "hello word";
  cout << "str1 = " << str1 << endl;

  string str2;
  str2 = str1;
  cout << "str2 = " << str2 << endl;

  string str3;
  str3 = 'a'; //不常用
  cout << "str3 = " << str3 << endl;

  string str4;
  str4.assign("hi ");
  cout << "str4 = " << str4 << endl;

  string str5;
  str5.assign("hello string",7); //把字符串str5的前7个字符(包含空格)赋给当前字符串
  cout << "str5 = " << str5 << endl;

  string str6;
  str6.assign(str5);
  cout << "str6 = " << str6 << endl;

  string str7;
  str7.assign(10, 'z');
  cout << "str7 = " << str7 << endl;
}
int main() {
  test();
  return 0;
}

字符串string赋值方式多以operator= 为主,assign()使用较少

3.string 字符串拼接

#include <iostream>
using namespace std;
#include <string>

// string 字符串拼接

void test() {
  //重载+=操作符
  string str1 = "我";
  str1 += "爱学习";
  cout << "str1 = " << str1 << endl;

  str1 += ':'; //末尾单追加一个字符
  // str1 += '吗';   //末尾单追加一个字符,错误,'吗'非字符
  cout << "str1 = " << str1 << endl;

  string str2 = " Book Tool";
  str1 += str2; //追加一个string的字符串
  cout << "str1 = " << str1 << endl;

  // append
  string str3 = "I";
  str3.append(" Love"); //把字符串连接到当前字符串结尾
  cout << "str3 = " << str3 << endl;

  str3.append(" study book",
              6); //把字符串study book的前6个字符连接到当前字符串的结尾
  cout << "str3 = " << str3 << endl;

  //   str3.append(str2);
  //   cout << "str3 = " << str3 << endl;

  str3.append(str2, 0, 5); //从str2字符串的第0个位置开始截取5个字符连接到字符串结尾 只截取Book,包含Book前的空格(是第0个位置)
  cout << "str3 = " << str3 << endl;
}

int main() {
  test();
  return 0;
}




输出:


str1 = 我爱学习
str1 = 我爱学习:
str1 = 我爱学习: Book Tool
str3 = I Love
str3 = I Love study
str3 = I Love study Book


4.string 查找和替换

#include <iostream>
using namespace std;
#include <string>

// string 查找和替换

// 1查找 //一般用find即可
void test01() {
  //   string str1 = "abcdefg"; // a是第0个位置
  string str1 = "abcdefgde"; // a是第0个位置 g是第6个位置
  int pos =
      str1.find("de"); // find 返回的是int类型,找到就返回所在位置,未找到返回-1

  if (pos == -1) {
    cout << " 未找到字符串" << endl;
  } else {
    cout << "找到字符串 pos = " << pos << endl;
  }

  // rfind 和 find 区别
  // rfind 从右往左查找; find 从左往右查找
  pos = str1.rfind("de");
  cout << "pos = " << pos << endl;
}

//替换
void test02() {
  string str2 = "abcdefg";

  //从1号位置起(b) 3个字符(也即bcd)替换为"pppp"
  str2.replace(1, 3, "pppp");
  cout << " str2 = " << str2 << endl;
}

int main() {
  test01();
  test02();
  return 0;
}




输出:



找到字符串 pos = 3
pos = 7
 str2 = appppefg


5.string 字符串比较

#include <iostream>
using namespace std;
#include <string>

// string 字符串比较 compare最大的用途比较两个字符串是否相等,判断谁大谁小以及比较中文字符串的意义不大。

void test01() {
  // str1和str2字符串逐个位置的字符比较
  string str1 = "hello";
  string str2 = "hello";
  if (str1.compare(str2) == 0) {
    cout << "str1 = str2" << endl;
  }

  string str3 = "xello"; // x>h ,返回1
  string str4 = "hello";
  if (str3.compare(str4) > 0) {
    cout << "str3 > str4" << endl;
  }

  string str5 = "hello"; // h<x ,返回-1
  string str6 = "xello";
  if (str5.compare(str6) < 0) {
    cout << "str5 < str6" << endl;
  }
}

int main() {
  test01();
  return 0;
}




输出:


str1 = str2
str3 > str4
str5 < str6







string 字符串比较 compare最大的用途比较两个字符串是否相等,判断谁大谁小以及比较中文字符串的意义不大。

6.string 字符存取

#include <iostream>
using namespace std;
#include <string>

// string 字符存取

void test01() {
  string str = "hello";

  // 1 通过[]访问单个字符

  for (int i = 0; i < str.size(); i++) {
    cout << str[i] << "   ";
  }
  cout << endl;

  // 2 通过at方式访问单个字符

  for (int i = 0; i < str.size(); i++) {
    cout << str.at(i) << "   ";
  }
  cout << endl;

  //修改单个字符
  str[0] = 'x';
  // xello
  cout << "str = " << str << endl;

  str.at(1) = 'x'; //修改1号位置的字符xxllo
  cout << "str = " << str << endl;
}
int main() {
  test01();
  return 0;
}




输出:


h   e   l   l   o   
h   e   l   l   o   
str = xello
str = xxllo

7.string 字符串插入和删除

#include <iostream>
using namespace std;
#include <string>

// string 插入和删除  //插入和删除起始下标都是从0开始

void test() {
  string str = "hello";

  //插入
  str.insert(1, "aaa"); //在1号位置插入"aaa"
                        // haaaello

  cout << " str = " << str << endl;

  //删除
  str.erase(1, 3); //从第一个位置起删除3个
  cout << " str = " << str << endl;
}

int main() {
  test();
  return 0;
}


输出:

 str = haaaello  //插入
 str = hello      //删除

8.string 子串获取

#include <iostream>
using namespace std;
#include <string>

// string 求子串

void test() {
  string str = "hello";
  string subStr = str.substr(1, 3); //从1号位置起截取3个 //ell
  cout << "subStr =" << subStr << endl;
}

//实用操作
void test02() {
  string email = "zhangsan@163.com";

  //从邮箱地址中 获取 用户名信息
  //   string name = email.substr(0, 8);
  //   cout << "name = " << name << endl;

  //通过找@符号之前的字符来获取
  //先找到@符号的位置
  //   int pos = email.find('@');//23-24find中传入参数的形式均可
  int pos = email.find("@");
  cout << " pos = " << pos << endl;
  string userName = email.substr(0, pos);
  cout << "userName = " << userName << endl;
}

int main() {
  test();
  test02();
  return 0;
}


输出:

subStr =ell
 pos = 8
userName = zhangsan

9.string 字符串长度获取

1.length()成员函数

length()函数是string的内置成员方,用于返回string类型字符串的实际长度
length()函数声明:

// 返回 string 长度,单位字节
size_t length() const noexcept;

示例1:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string s= "hello world!";
    cout << s.length() << endl;
    return 0;
}


输出:

12

2.size()成员函数

size()函数与length()一样,没有本质区别。string类刚开始只有length()函数,延续了C语言的风格。引入STL之后,为了兼容又加入了size,这样就可以方便的使用于STL的算法。

size()函数声明:

// 返回 string 长度,单位字节。作用等同于 length()
size_t size() const noexcept;

示例2:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string s= "hello world!";
    cout << s.size() << endl;
    return 0;
}


输出:

12

3.借助strlen()函数

strlen函数:计算字符串str的长度,从字符的首地址开始遍历,以 ‘\0’ 为结束标志,然后将计算的长度返回,计算的长度并不包含’\0’。

因为 strlen() 函数是用于 C 风格字符串的,因此要使用 c_str() 成员函数来获取 string 对象的 C 风格字符串表示,然后将它传递给 strlen() 函数。

strlen()函数声明:

// C 标准库函数,返回C风格字符串长度,单位字节 size_t
strlen ( const char * str );
const char * str常量指针,指针的指向可以更改,但是指针指向的值不能更改。

示例3:

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
    string s= "hello world!";
    cout << strlen(s.c_str()) << endl;
    return 0;
}

输出:

12

4.注意事项

(1)length()方法和size()方法是不受结束标志‘\0’ ,返回的是字符串的实际长度,而strlen() 函数遇到结束标志‘\0’就停止,返回的是遇到的第一个结束标志前的字符串长度。下面看一个例子:

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
    char buf[10] = { 0 };
    buf[0] = 'a';
    buf[2] = 'v';
    buf[3] = 'h';
    buf[4] = '\0';

    string s(buf, 6); // 我们可以理解为将名为"s"的string变量通过构造函数从指定的char型数组"buf"中提取前6个元素进行初始化

    cout << "s:" << s << endl;
    cout << "length方法:" << s.length() << endl;
    cout << "size方法:" << s.size() << endl;
    cout << "strlen方法:"<< strlen(s.c_str()) << endl;
    return 0;
}

注意:char buf[10] = { 0 }是只给buf数组的第一个元素赋结束标志’\0‘,剩余的9个元素没进行赋值操作,也都为结束标志’\0’。

从结果中可以看到,length()和size()方法返回的是字符串的实际长度,而strlen方法则是受到’\0‘的影响进行截断了。

(2)此外这里还有一个坑需要注意:

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
    string s= "hello\0 world!";
    cout << "length方法:" << s.length() << endl;
    cout << "size方法:" << s.size() << endl;
    cout << "strlen方法:"<< strlen(s.c_str()) << endl;
    return 0;
}

string是C++的一个类,在string s= “hello\0 world!”;这行代码中,它的构造函数是借助了strlen函数实现的。

因此,实际上s字符串只取到了’\n‘前面的字符串,后面的都被截断了。

参考:C++中求string类型字符串长度的三种方法_c++字符串长度-CSDN博客

一、string作为行参的使用

1.作为函数的形参来接收字符串

在 C++ 中,可以将 std::string 作为函数的形参来接收字符串

示例代码如下:

#include <iostream>
#include <string>

void printString(const std::string &str) {
  std::cout << "传入的字符串是:" << str << std::endl;
}

int main() {
  std::string myString = "Hello, World!";
  printString(myString);
  printString("Hello, World!"); //直接传入字符串进行打印

  std::string str1 = "Hello"; // 声明并初始化一个字符串
  std::string str2("World");  // 使用构造函数声明并初始化一个字符串
  std::string str3 = str1 + " " + str2; // 字符串拼接
  printString(str3);
  return 0;
}



输出:

传入的字符串是:Hello, World!
传入的字符串是:Hello, World!
传入的字符串是:Hello World


        在上述代码中,我们定义了一个名为 printString 的函数,它接受一个 std::string 类型的参数 str。在 main 函数中,我们创建了一个 std::string 类型的变量 myString,并将其作为参数传递给 printString 函数。在函数体内,我们可以像操作任何其他变量一样使用 str,可以对其进行输出、处理、拼接等操作。

注意:

        需要注意的是,当字符串作为形参传递给函数时,会进行字符串的复制操作。如果字符串较长或需要频繁调用,可能会带来一定的性能开销。如果不需要修改字符串,可以将字符串作为 const std::string& 类型的形参来传递,避免不必要的复制。


总结

        本文对string类常见的使用进行了总结归纳。

        声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

参考:

1. 25 string容器-字符串拼接_哔哩哔哩_bilibili

2. c++的string怎么作为形参使用 - 问答 - 亿速云

  • 19
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在C++中,stringstream是一个类似于字符串流的对象,它可以用于字符串和其他数据类型之间的转换。可以使用stringstream来清空、拼接字符串,以及将不同类型的数据转换为字符串。 引用中的代码示例展示了如何清空stringstream对象。可以使用clear()方法或者str("")方法来清空stringstream。当需要进行多次数据类型转换时,使用clear()方法是必要的,而str("")方法适用于其他场景。 引用中的代码示例展示了一个将多个字符串拼接到stringstream中,并将其转换为string类型的示例。使用sstream的str()方法可以将其转换为string类型。 引用中的代码示例展示了如何使用stringstream将int类型转换为string类型。可以将int类型的值放入输入流中,然后从sstream中抽取该值并赋给string类型。 总结起来,stringstream在C++中用于字符串和其他数据类型之间的转换,可以实现字符串的拼接、清空以及类型转换等功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [C++ stringstream](https://blog.csdn.net/Sakuya__/article/details/122751238)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值