字符串(二):string

摘要:
字符串使用方法排序系列:字符串(1):字符数组字符串(2):字符串字符串是C++STL的字符串类型,原型是vector,字符串处理已经优化。我们还可以使用类似于vector:迭代器的string::iterator迭代器来遍历字符串,例如:for(string::iterator=str.begin();i!=str.end();I++){//dothingshere}注意:像vector中的用法一样,在迭代迭代器时修改字符串的内容长度可能会出现意外错误。

字符串使用方法整理 系列:


string 是 C++ STL 的一个字符串类型,原型是 vector<char> 并对字符串处理做了优化。

1. 声明

首先要包括库文件 #include <string>,这个 <string> 不同于 <cstring>,是 C++ 专有的库文件。

然后做出声明:

string str;

特殊的,可以赋予 string 初始值:

string a = "text";
string b("text");
string c = a; // 以 string 对 string 赋值也是可以的

2. 访问元素

2.1 直接访问

函数 .length() 可以得到该 string 的长度。

我们可以直接通过元素下标来访问某一个 string 中的字符,如 str[2] 访问第三个字符。

2.2 迭代器

我们也可以使用 vector<char> 相似的函数,如 .size() 是和 .length() 用途相同的函数。

我们也可以使用类似 vector<char>::iteratorstring::iterator 迭代器来遍历字符串,如:

for (string::iterator i = str.begin(); i != str.end(); i++) {
    // do things here
}

注意:同 vector 中的用法一样,通过迭代器遍历 string 时修改 string 的内容长度(如删除 string 中的字符)可能有意想不到的错误。

参考:C++ Reference 官网对 string 类中迭代器函数的定义如下:

begin: Return iterator to beginning (public member function )

end: Return iterator to end (public member function )

rbegin: Return reverse iterator to reverse beginning (public member function )

rend: Return reverse iterator to reverse end (public member function )

cbegin: Return const_iterator to beginning (public member function )

cend: Return const_iterator to end (public member function )

crbegin: Return const_reverse_iterator to reverse beginning (public member function )

crend: Return const_reverse_iterator to reverse end (public member function )

2.3 赋值函数

.assign(...) 赋值函数:

s.assign(str);
s.assign(str, 1, 3); //如果str是"iamangel" 就是把"ama"赋给字符串
s.assign(str, 2, string::npos); //把字符串str从索引值2开始到结尾赋给s
s.assign("gaint");
s.assign("nico", 5); //把’n’ ‘I’ ‘c’ ‘o’ ‘’赋给字符串
s.assign(5, ’x’); //把五个x赋给字符串

3. 操作

3.1 清空 .clear()

用来清空 string。

3.2 判断空 .empty()

返回一个 boolean 值表示 string 是否为空。

3.3 取头部 .front()

返回首字符

3.4 取尾部 .back()

返回尾字符。

3.5 字符串相加

string 重载了 + 符号和 += 符号,使用方法显而易见。+= 符号与 .append(...) 函数作用相同。如果注重函数式编程,推荐使用 .append(...) 函数。

3.6 插入 .insert(...)

.insert(...) 函数的作用是在字符串某处插入字符(串)。定义如下:

string (1)

string& insert (size_t pos, const string& str);

substring (2)

string& insert (size_t pos, const string& str, size_t subpos, size_t sublen);

c-string (3)

string& insert (size_t pos, const char* s);

buffer (4)

string& insert (size_t pos, const char* s, size_t n);

fill (5)

string& insert (size_t pos, size_t n, char c);
void insert (iterator p, size_t n, char c);

single character (6)

iterator insert (iterator p, char c);

range (7)

template <class InputIterator>
void insert (iterator p, InputIterator first, InputIterator last);

C++ Reference 官网的例子:

// 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 << '
';
  return 0;
}

3.7 删除 .erase(...)

.erase(...) 函数可以删除指定位置的字符(串)。定义如下:

sequence (1) string& erase (size_t pos = 0, size_t len = npos);

character (2) iterator erase (iterator p);

range (3) iterator erase (iterator first, iterator last);

举个例子(来自 C++ Reference):

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

int main ()
{
  std::string str ("This is an example sentence.");
  std::cout << str << '
';
                                           // "This is an example sentence."
  str.erase (10,8);                        //            ^^^^^^^^
  std::cout << str << '
';
                                           // "This is an sentence."
  str.erase (str.begin()+9);               //           ^
  std::cout << str << '
';
                                           // "This is a sentence."
  str.erase (str.begin()+5, str.end()-9);  //       ^^^^^
  std::cout << str << '
';
                                           // "This sentence."
  return 0;
}

3.8 替换 .replace(...)

.replace(...) 函数定义:

string (1)

string& replace (size_t pos,  size_t len,  const string& str);
string& replace (iterator i1, iterator i2, const string& str);

substring (2)

string& replace (size_t pos,  size_t len,  const string& str,
                 size_t subpos, size_t sublen);

c-string (3)

string& replace (size_t pos,  size_t len,  const char* s);
string& replace (iterator i1, iterator i2, const char* s);

buffer (4)

string& replace (size_t pos,  size_t len,  const char* s, size_t n);
string& replace (iterator i1, iterator i2, const char* s, size_t n);

fill (5)

string& replace (size_t pos,  size_t len,  size_t n, char c);
string& replace (iterator i1, iterator i2, size_t n, char c);

range (6)

template <class InputIterator>
  string& replace (iterator i1, iterator i2,
                   InputIterator first, InputIterator last);

举个例子(来自 C++ Reference):

// replacing in a string
#include <iostream>
#include <string>

int main ()
{
  std::string base="this is a test string.";
  std::string str2="n example";
  std::string str3="sample phrase";
  std::string str4="useful.";

  // replace signatures used in the same order as described above:

  // Using positions:                 0123456789*123456789*12345
  std::string str=base;           // "this is a test string."
  str.replace(9,5,str2);          // "this is an example string." (1)
  str.replace(19,6,str3,7,6);     // "this is an example phrase." (2)
  str.replace(8,10,"just a");     // "this is just a phrase."     (3)
  str.replace(8,6,"a shorty",7);  // "this is a short phrase."    (4)
  str.replace(22,1,3,'!');        // "this is a short phrase!!!"  (5)

  // Using iterators:                                               0123456789*123456789*
  str.replace(str.begin(),str.end()-3,str3);                    // "sample phrase!!!"      (1)
  str.replace(str.begin(),str.begin()+6,"replace");             // "replace phrase!!!"     (3)
  str.replace(str.begin()+8,str.begin()+14,"is coolness",7);    // "replace is cool!!!"    (4)
  str.replace(str.begin()+12,str.end()-4,4,'o');                // "replace is cooool!!!"  (5)
  str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful."    (6)
  std::cout << str << '
';
  return 0;
}

4. 杂项

4.1 比较

通过 <, >, ==, <=, >=, != 六种比较符号,可以方便地在 string 之间、甚至是在 string 和 c-string 之间进行比较。

.compare(...) 支持多参数处理,支持用索引值和长度定位子串来进行比较。返回一个整数来表示比较结果,返回值意义如下:

0:相等

> 0:大于

< 0:小于

举例如下:

string s("abcd");

s.compare("abcd"); //返回0
s.compare("dcba"); //返回一个小于0的值
s.compare("ab"); //返回大于0的值

s.compare(s); //相等
s.compare(0, 2, s, 2, 2); //用"ab"和"cd"进行比较 小于零
s.compare(1, 2, "bcx", 2); //用"bc"和"bc"比较。

4.2 取子串 .substr(...)

取子串函数 .substr(...):

s.substr(); //返回s的全部内容
s.substr(11); //从索引11往后的子串
s.substr(5, 6); //从索引5开始6个字符

4.3 查找 .find(...)

.find(...) 函数的定义:

string (1)

size_t find (const string& str, size_t pos = 0) const;

c-string (2)

size_t find (const char* s, size_t pos = 0) const;

buffer (3)

size_t find (const char* s, size_t pos, size_t n) const;

character (4)

size_t find (char c, size_t pos = 0) const;

返回值为字符串中第一个匹配的位置;如果没有找到则返回 string::npos 值。

样例(来自 C++ Reference):

// string::find
#include <iostream>       // std::cout
#include <string>         // std::string

int main ()
{
  std::string str ("There are two needles in this haystack with needles.");
  std::string str2 ("needle");

  // different member versions of find in the same order as above:
  std::size_t found = str.find(str2);
  if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '
';

  found=str.find("needles are small",found+1,6);
  if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '
';

  found=str.find("haystack");
  if (found!=std::string::npos)
    std::cout << "'haystack' also found at: " << found << '
';

  found=str.find('.');
  if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '
';

  // let's replace the first needle:
  str.replace(str.find(str2),str2.length(),"preposition");
  std::cout << str << '
';

  return 0;
}

4.4 reserve 函数

参见:Link link


Further reading:

  1. C++ Reference Link link
  2. std::string Link link

免责声明:文章转载自《字符串(二):string》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇CentOS7 启动防火墙 报错 Failed to start iptables.service: Unit not found.Unity 多屏(分屏)显示,Muti_Display下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

记一次 synchronized 锁字符串引发的坑兼再谈 Java 字符串

业务有一个需求,我把问题描述一下: 通过代理IP访问国外某网站N,每个IP对应一个固定的网站N的COOKIE,COOKIE有失效时间。 并发下,取IP是有一定策略的,取到IP之后拿IP对应的COOKIE,发现COOKIE超过失效时间,则调用脚本访问网站N获取一次数据。 为了防止多线程取到同一个IP,同时发现该IP对应的COOKIE失效,同时去调用脚本更新...

Java中将String格式的标准时间字符串转换为Date格式的方法

场景 前端在往后端传递时间参数时,传递的是标准时间格式的字符串。 比如下面的lxyf参数 怎样将其转换为Date格式。 注: 博客:https://blog.csdn.net/badao_liumang_qizhi关注公众号霸道的程序猿获取编程相关电子书、教程推送与免费下载。 实现 调用如下转换格式的方法 Date lxyfDate = str2Date...

Qt中文乱码问题(比较清楚,同一个二进制串被解释成不同的语言)

文章来源:http://blog.csdn.net/brave_heart_lxl/article/details/7186631 以下是dbzhang关于qt中文乱码问题原因的阐述,觉得不错: 首先呢,声明一下,QString 是不存在中文支持问题的,很多人遇到问题,并不是本身 QString 的问题,而是没有将自己希望的字符串正确赋给QString。...

Windows PowerShell初体验——.NET对象支持

我个人很少用到Linux/Unix 操作系统. 对于不少Linux/Unix管理员在系统任务操作Shell一直保持很难理解. 后来从朋友公司听说他们测试队伍中专门保留了一个脚本Scirpt Shell 测试小组. 我一时更纳闷了. 当然这个问题知道我碰到Windows PowerShell-Windows出的一套Shell工具后 才渐渐理解. Window...

C/C++迭代器使用具体解释

迭代器是一种检查容器内元素并遍历元素的数据类型。能够替代下标訪问vector对象的元素。 每种容器类型都定义了自己的迭代器类型,如 vector: vector<int>::iterator iter;这符语句定义了一个名为 iter 的变量。它的数据类型是 vector<int> 定义的 iterator 类型。每一个标准库容器...

Java中针对Yaml格式数据操作记录

写在前面 最近由于涉及的功能需要对Nacos配置信息通过代码实现发布,在此过程中,涉及到String字符串转换Map,Map转换为Yaml格式的字符串等方法,由于之前没有接触过此方面内容,所以特在此进行记录,以做备忘! 1、Nacos获取配置 Nacos获取配置信息,返回结果为String格式字符串,这里可以参看Nacos中文文档(地址为:https://...