C++——string类的使用

1、string的构造

        在  c plus plus  这个网站上可以查到相关的信息,

(1)是无参构造函数(也是默认构造),就是一个空字符串

(2)是一个拷贝构造,传入一个参数构造字符串

 (3)是一个有参构造,参数有点复杂,他有一个字符串,在字符串的pos位置,取len个字符,这个len有缺省值,len=npos,npos是一个无符号整型的-1,表示此类型的最大值,也就是无符号整形中最大的值,

假设我们不给len传参,就是从pos位置,取到字符串的末尾,然后赋值给s3;

我们给len赋值,就是从pos位置取len个字符,然后赋值给s3;

 (4)是用一个C-string来构建,C-string指的就是结尾带/0的字符串,

(5)是取字符串前n个字符

 (6)是构造n个’c'字符,组成字符串

标红的用的比较多,要重点记

2、string类对象的容量操作

1.size  

 返回字符串有效字符长度;

返回的字符的个数,但是不包括  ‘\0’, 其实string类的结尾是有\0的,因为要兼容C语言,

 2.length

返回字符串有效字符长度,作用和size差不多,但我们经常用size;

3.resize

调整字符串大小

将字符串大小调整为 n 个字符的长度

如果 n 小于当前字符串长度,则当前值将缩短为其第一个 n 个字符,从而删除第 n个字符之外的字符。

如果 n 大于当前字符串长度,则通过在末尾插入所需数量的字符来扩展当前内容,以达到 n 的大小。如果指定了 c,则新元素将初始化为 c 的副本,否则,它们是值初始化的字符(空字符)。

注意:

当我们要插入字符时,从字符串末尾的位置插入,也就是\0的位置最后一行打印的,末尾其实还有5个\0,我们看不出来,

4.capacity

返回空间总大小

因为字符串可以自动扩容,所以他有个容量接口,但是不同编译器下,扩容的规则不一样,有的是二倍扩容,有的是1.5倍扩容,

5.max_size

字符串的最大长度

max_size是指在当前环境下,可以达到字符串的最大长度;

6.reserve

为字符串预留空间

string s1.reserve(100);

就是为字符串一次性开辟100个字节的空间,比较方便;

7.clear

清空有效字符

清除一个string类的有效字符,但是空间还在,

8.empty

判断字符串是否为空

9.reverse

反转字符串

这个好像涉及到迭代器,比如我们要反转一个字符串

reverse( s1.begin(),s1.end() )

这样写就可以了

3、operator[]以及string类的遍历

string类还重载了[]类型,可以去到字符的下标,和数组类似,

// 1. for+operator[]
	for (size_t i = 0; i < s.size(); ++i)
		cout << s[i] << endl;

	// 2.迭代器
	string::iterator it = s.begin();
	while (it != s.end())
	{
		cout << *it << endl;
		++it;
	}

	// string::reverse_iterator rit = s.rbegin();
	// C++11之后,直接使用auto定义迭代器,让编译器推到迭代器的类型
	auto rit = s.rbegin();
	while (rit != s.rend())
		cout << *rit << endl;

	// 3.范围for
	for (auto ch : s)
		cout << ch << endl;
}

4、string类对象的修改操作

1.operator+=

字符串可以+=一个字符串或者字符或string类

非常好用

2.append

追加字符串

不过平时用的少,我们可以通过一些例子来说明:
 

void test_string3()
{
	std::string str;
	std::string str2 = "Writing ";
	std::string str3 = "print 10 and then 5 more";

	// used in the same order as described above:
	str.append(str2);                       // "Writing "
	str.append(str3, 6, 3);                   // "10 "
	str.append("dots are cool", 5);          // "dots "
	str.append("here: ");                   // "here: "
	str.append(10u, '.');                    // "..........",10u表示10是一个无符号整形
	str.append(str3.begin() + 8, str3.end());  // " and then 5 more"

	std::cout << str << '\n';
}

3.push_back

尾插一个字符,空间不够自动扩容

4.assign

替换当前字符串的值

和append格式一样,但是作用不一样;

// string::assign
#include <iostream>
#include <string>

int main ()
{
  std::string str;
  std::string base="The quick brown fox jumps over a lazy dog.";

  // used in the same order as described above:

  str.assign(base);
  std::cout << str << '\n';

  str.assign(base,10,9);
  std::cout << str << '\n';         // "brown fox"

  str.assign("pangrams are cool",7);
  std::cout << str << '\n';         // "pangram"

  str.assign("c-string");
  std::cout << str << '\n';         // "c-string"

  str.assign(10,'*');
  std::cout << str << '\n';         // "**********"

  str.assign<int>(10,0x2D);
  std::cout << str << '\n';         // "----------"

  str.assign(base.begin()+16,base.end()-12);
  std::cout << str << '\n';         // "fox jumps over"

  return 0;
}

5.insert

在字符串中插入其他字符串

样例: 

// inserting into a string
#include <iostream>
#include <string>

int main ()
{
  std::string str="to be question";
  std::string str2="the ";
  std::string str3="or not to be";
  std::string::iterator it;

  // used in the same order as described above:
  str.insert(6,str2);                 // to be (the )question
  str.insert(6,str3,3,4);             // to be (not )the question
  str.insert(10,"that is cool",8);    // to be not (that is )the question
  str.insert(10,"to be ");            // to be not (to be )that is the question
  str.insert(15,1,':');               // to be not to be(:) that is the question
  it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
  str.insert (str.end(),3,'.');       // to be, not to be: that is the question(...)
  str.insert (it+2,str3.begin(),str3.begin()+3); // (or )

  std::cout << str << '\n';
  return 0;
}

6.erase

销毁当前字符串

7.replace

替换 字符串的一部分 

和assign的区别是,assign把整个字符串都替换了,replace可以替换部分字符串

5、string类对象的字符串操作

1.c_str

把string类转化成字符串类型;

2.copy

从字符串中赋值一段字符串,赋值给指定的字符数组

 

// string::copy
#include <iostream>
#include <string>

int main ()
{
  char buffer[20];
  std::string str ("Test string...");
  std::size_t length = str.copy(buffer,6,5);
  buffer[length]='\0';
  std::cout << "buffer contains: " << buffer << '\n';
  return 0;
}

 3.find

在字符串里查找字符或者字符串或者string类

(3)的意思是在字符串中查找s,在pos位置,查找s的n个字符;

4.rfind

倒着查找,其他的和find一样

5.substr

在字符串中从pos位置开始,截取n个字节,然后返回

// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

 6.getline

流输入一行字符串

通常我们用的cin输入,遇到空格或者换行就会停止,用getline可以很好的解决这个问题,

#include <iostream>
#include <string>

int main ()
{
  std::string name;

  std::cout << "Please, enter your full name: ";
  std::getline (std::cin,name);
  std::cout << "Hello, " << name << "!\n";

  return 0;
}

 

自己熟悉一下,不如看文档!

相关推荐

  1. MFC中CString用法及使用示例

    2024-04-29 12:54:04       19 阅读
  2. 详解QUuid使用

    2024-04-29 12:54:04       12 阅读
  3. Scanner使用步骤

    2024-04-29 12:54:04       16 阅读
  4. QtQDir使用示例

    2024-04-29 12:54:04       32 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-29 12:54:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-29 12:54:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-29 12:54:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-29 12:54:04       18 阅读

热门阅读

  1. 软件测试_边界值法

    2024-04-29 12:54:04       12 阅读
  2. CommentServiceImpl

    2024-04-29 12:54:04       12 阅读
  3. [SqlServer数据库:基于容器化]:快速部署安装

    2024-04-29 12:54:04       14 阅读
  4. 小程序API wx.startLocationUpdateBackground 的使用

    2024-04-29 12:54:04       10 阅读
  5. QT5之lambda

    2024-04-29 12:54:04       12 阅读
  6. C++ day5

    C++ day5

    2024-04-29 12:54:04      11 阅读
  7. C++中的时间相关处理

    2024-04-29 12:54:04       13 阅读
  8. python基础知识

    2024-04-29 12:54:04       12 阅读
  9. Unity坐标相关——坐标系,单位

    2024-04-29 12:54:04       13 阅读
  10. Node.js 的 fs 模块分析及其应用

    2024-04-29 12:54:04       16 阅读
  11. 使用动态ip上网稳定吗?

    2024-04-29 12:54:04       13 阅读
  12. 安装k8s

    2024-04-29 12:54:04       12 阅读
  13. web server apache tomcat11-20-connectors 连接器

    2024-04-29 12:54:04       14 阅读