C++——std::String

写在前面

这一篇博客系统学习一下C++中String类的相关函数。这个类在之前做题的时候就经常遇到,其实说白了,它也就是一个vector < char >。但是,它又有一些独特的函数,可以在做题的时候简化代码,提高效率。所以在这一篇博客,就根据CPlusPlus官网中< string >中的内容做一个整理。
自己整理之外,还有一些优秀的整理资料可供参考:std::string用法总结

string类与头文件包含

string即为字符串。string是C++标准库的一个重要的部分,主要用于字符串处理。可以使用输入输出流方式直接进行操作,也可以通过文件等手段进行操作。同时C++的算法库对string也有着很好的支持,而且string还和c语言的字符串之间有着良好的接口。虽然也有一些弊端,但是瑕不掩瑜。 头文件引用如下:

#include <string>  

string::string

以下代码是string构造的几种方法,代码来自std::string::string

// string constructor
#include <iostream>
#include <string>

int main ()
{
  std::string s0 ("Initial string");  //根据已有字符串构造新的string实例

  // constructors used in the same order as described above:
  std::string s1;             //构造一个默认为空的string
  std::string s2 (s0);         //通过复制一个string构造一个新的string
  std::string s3 (s0, 8, 3);    //通过复制一个string的一部分来构造一个新的string。8为起始位置,3为偏移量。
  std::string s4 ("A character sequence");  //与s0构造方式相同。
  std::string s5 ("Another character sequence", 12);  //已知字符串,通过截取指定长度来创建一个string
  std::string s6a (10, 'x');  //指定string长度,与一个元素,则默认重复该元素创建string
  std::string s6b (10, 42);      // 42 is the ASCII code for '*'  //通过ASCII码来代替s6a中的指定元素。
  std::string s7 (s0.begin(), s0.begin()+7);  //通过迭代器来指定复制s0的一部分,来创建s7

  std::cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
  std::cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6a: " << s6a;
  std::cout << "\ns6b: " << s6b << "\ns7: " << s7 << '\n';
  return 0;
}

//Output:
//s1: 
//s2: Initial string
//s3: str
//s4: A character sequence
//s5: Another char
//s6a: xxxxxxxxxx
//s6b: **********
//s7: Initial

总结一下,string创建的方式相当灵活。我在此尝试对上面所述方法进行一个简单的分类整理:

  • 无任何参数:按照默认方式构造一个空string。
  • 已知字符串”abcde…”:可以将已知字符串作为参数传入,也可以传入一个int型参数,i,意为取已知字符串从0到i-1长度的子字符串。或者传入两个int型i,j,前一个int指起始位置i,从i+1开始数j个元素作为新子字符串。
  • 指定sting长度:指定string长度i,与字符a,则默认重复a直到string长度为i。这里字符可以是ASCII码,也可以直接打出’a’。
  • 已知string:可以根据别的string创建新的string。传入名称,则全部复制,传入名称且加上迭代器指定的起始位置与终止位置可以复制被拷贝string 的一部分。

string::operation =

使用 = 运算符也可以创建string。可参考如下代码:

// string assigning
#include <iostream>
#include <string>

int main ()
{
  std::string str1, str2, str3;
  str1 = "Test string: ";   // c-string       //通过=运算符来给已创建的string“赋值”
  str2 = 'x';               // single character
  str3 = str1 + str2;       // string         
  //注意这里重载了"+",string类的"+"可以理解为胶水,将两个string类型连接起来了

  std::cout << str3  << '\n';
  return 0;
}
//Output:
//Test string: x

string-Iterators

string也有迭代器,熟练掌握迭代器的使用,有时能避免繁杂的for循环,但代码更有灵活性。

这里写图片描述

可以使用迭代器来实现遍历,代码如下:

// string::begin/end
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)
    std::cout << *it;
  std::cout << '\n';

  return 0;
}
//Output:
//Test string

string-capacity

这里写图片描述

1.string::size:返回string的长度。示例代码如下

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

int main ()
{
  std::string str ("Test string");
  std::cout << "The size of str is " << str.size() << " bytes.\n";
  return 0;
}
//Output:
//The size of str is 11 bytes

2.string::length:返回string的长度。示例代码如下

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

int main ()
{
  std::string str ("Test string");
  std::cout << "The size of str is " << str.length() << " bytes.\n";
  return 0;
}
//Output:
//The size of str is 11 bytes

比较一下size与length,其实二者没有任何区别,length是因为沿用C语言的习惯而保留下来的,string类最初只有length,引入STL之后,为了兼容又加入了size,它是作为STL容器的属性存在的,便于符合STL的接口规则,以便用于STL的算法。

3.string::capacity:返回在重新分配内存之前,string所能包含的最大字符数。
4.string::max_size:返回一个string最多能够包含的字符数。以上两个函数示例代码参见如下:

// comparing size, length, capacity and max_size
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  std::cout << "size: " << str.size() << "\n";
  std::cout << "length: " << str.length() << "\n";
  std::cout << "capacity: " << str.capacity() << "\n";
  std::cout << "max_size: " << str.max_size() << "\n";
  return 0;
}

//A possible output for this program could be:
//size: 11
//length: 11
//capacity: 15
//max_size: 4294967291

更加详细的解释可以参考:STL:string 大小(Size)和容量(Capacity)

5.string::resize:将string的长度更改为一个指定参数的长度。如果n小于当前字符串的长度,则将当前值缩短为前n个字符,除去超出n的字符。如果n大于当前字符串长度,则通过在最后插入尽可能多的字符以达到大小n来扩展当前内容。 如果指定了c,则将新元素初始化为c的副本,否则,它们是值初始化的字符(空字符)。

示例代码如下:

// resizing string
#include <iostream>
#include <string>

int main ()
{
  std::string str ("I like to code in C");
  std::cout << str << '\n';

  unsigned sz = str.size();

  str.resize (sz+2,'+');
  std::cout << str << '\n';

  str.resize (14);
  std::cout << str << '\n';
  return 0;
}
//Output:
//I like to code in C
//I like to code in C++
//I like to code

6.string::reserve:请求更改容量。要求字符串容量适应规划的尺寸变化,长度最多为n个字符。如果n大于当前的字符串容量,该函数将使容器将其容量增加到n个字符(或更大)。在所有其他情况下,它将作为一个无约束的请求来缩小字符串容量:容器实现可以自由地进行优化,并且使字符串的容量大于n。这个函数对字符串长度没有影响,也不能改变它的内容。

其实简单点说,就是该函数更改了string的容量capaticy,并没有实际更改size。更多内容可以参考vector的reserve和resize

7.string::clear:擦除字符串的内容,成为一个空字符串(长度为0个字符)。调用方式:

str.clear();

8.string::empty:判断string其中内容是否为空。再判断一个string是否为空时,可以使用该函数,也可以使用size()函数与length()函数来获取string的长度,然后判断长度是否为0。但优先使用empty()函数,因为该函数运行速度更快。

string-element access

这里写图片描述

1.string::operator[]:获取字符串的字符,返回字符串中位置pos处字符的引用。示例代码如下:

// string::operator[]
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  for (int i=0; i<str.length(); ++i)
  {
    std::cout << str[i];
  }
  return 0;
}
//Output:
//Test string

2.string::at:获取字符串中的字符,返回字符串中位置pos处字符的引用。该函数自动检查pos是否是字符串中字符的有效位置(即pos是否小于字符串长度),如果不是,则会抛出out_of_range异常。示例代码如下

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

int main ()
{
  std::string str ("Test string");
  for (unsigned i=0; i<str.length(); ++i)
  {
    std::cout << str.at(i);
  }
  return 0;
}
//Output:
//Test string

operator[]和at()均返回当前字符串中第n个字符的位置,但at函数提供范围检查,当越界时会抛出out_of_range异常,下标运算符[]不提供检查访问。[]访问的速度比at()要快,但不作越界检查.用[]访问之前, 要对下标进行检查( > string::npos && < string::size())

3.:string::back:访问最后一个字符,返回对字符串最后一个字符的引用。这个函数不能在空字符串上调用。

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

int main ()
{
  std::string str ("hello world.");
  str.back() = '!';
  std::cout << str << '\n';
  return 0;
}
//Output:
//hello world!  //将原来的最后一个'.' 变为了'!'。

4.string::front:访问第一个字符,返回对字符串的第一个字符的引用。与成员string :: begin不同,它将一个迭代器返回给这个相同的字符,这个函数返回一个直接引用。这个函数不能在空字符串上调用。

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

int main ()
{
  std::string str ("test string");
  str.front() = 'T';
  std::cout << str << '\n';
  return 0;
}
//Output:
//Test string   //将原来的第一个't'变为了'T'。

string-modifiers

这里写图片描述

1.string::operator+=:附加到字符串。通过在当前值的末尾添加其他字符来扩展字符串:

// string::operator+=
#include <iostream>
#include <string>

int main ()
{
  std::string name ("John");
  std::string family ("Smith");
  name += " K. ";         // c-string
  name += family;         // string
  name += '\n';           // character

  std::cout << name;
  return 0;
}
//Output:
//John K. Smith

2.string::append:附加到字符串。通过在当前值的末尾添加其他字符来扩展字符串:

// appending to string
#include <iostream>
#include <string>

int main ()
{
  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,'.');                    // ".........."
  str.append(str3.begin()+8,str3.end());  // " and then 5 more"
  str.append<int>(5,0x2E);                // "....."

  std::cout << str << '\n';
  return 0;
}
//Output:
//Writing 10 dots here: .......... and then 5 more.....

3.string::push_ back:追加字符到字符串。将字符c附加到字符串的末尾,将其长度增加1。与vector、set、map等容器的push_ back类似功能。

4.string::assign:将内容分配给字符串。为字符串分配一个新值,替换其当前内容。示例代码如下:

// 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"  //base的第11到第19个字符的内容

  str.assign("pangrams are cool",7);
  std::cout << str << '\n';         // "pangram"  //一个参数默认从头开始往后数7个字符,没有s

  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;
}
//Output:
//The quick brown fox jumps over a lazy dog.
//brown fox
//pangram
//c-string
//**********
//----------
//fox jumps over

5.string::insert:插入字符串。在由pos(或p)指示的字符之前的字符串中插入附加字符:

// 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:
  //后面注释中()括号的作用只是帮助显示插入的内容与位置信息。实际string中并没有这对括号
  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;
//Output:
//to be, or not to be: that is the question...
}

6.string::erase:擦除字符串中的字符。擦除部分字符串,减少其长度:

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

int main ()
{
  std::string str ("This is an example sentence.");
  std::cout << str << '\n';
  //后面注释有两部分,上一行是当前字符串内容,下一行是箭头,表示的意思就是箭头指向内容是处理的内容
                                           // "This is an example sentence."
  str.erase (10,8);                        //            ^^^^^^^^
  std::cout << str << '\n';                //消除第11到第19之间的字符。即" example",注意,有一个空格符
                                           // "This is an sentence."
  str.erase (str.begin()+9);               //           ^
  std::cout << str << '\n';                //消除第10个字符,即begin()后9个字符:'n'
                                           // "This is a sentence."
  str.erase (str.begin()+5, str.end()-9);  //       ^^^^^
  std::cout << str << '\n';                //消除begin()后5个字符,end()前9个字符。
                                           // "This sentence."
  return 0;
}

7.string::replace:替换字符串的一部分。替换以字符pos开头的字符串部分,并通过新内容跨越len字符(或[i1,i2之间的范围内的字符串部分)):

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

8.string::swap:交换字符串值。通过str的内容交换容器的内容,str是另一个字符串对象。 长度可能有所不同。在对这个成员函数的调用之后,这个对象的值是str在调用之前的值,str的值是这个对象在调用之前的值。请注意,非成员函数存在具有相同名称的交换,并使用与此成员函数相似的优化来重载该算法。

// swap strings
#include <iostream>
#include <string>

main ()
{
  std::string buyer ("money");
  std::string seller ("goods");

  std::cout << "Before the swap, buyer has " << buyer;
  std::cout << " and seller has " << seller << '\n';

  seller.swap (buyer);

  std::cout << " After the swap, buyer has " << buyer;
  std::cout << " and seller has " << seller << '\n';

  return 0;
//Output:
//Before the swap, buyer has money and seller has goods
// After the swap, buyer has goods and seller has money
}

9.string::pop_back:删除最后一个字符。擦除字符串的最后一个字符,有效地将其长度减1:

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

int main ()
{
  std::string str ("hello world!");
  str.pop_back();
  std::cout << str << '\n';
  return 0;
//Output:
//hello world
}

string:pop_ back与string:push_ back可以参考之前vector、set、map的使用方法。一样的。

string-string operations

这里写图片描述

1.string::c_str:获取C字符串等效。返回一个指向包含以空字符结尾的字符序列(即C字符串)的数组的指针,该字符串表示字符串对象的当前值。该数组包含相同的字符序列,这些字符组成字符串对象的值,并在末尾添加一个附加的终止空字符(’\ 0’)。

2.string::copy:从字符串复制字符序列。将字符串对象的当前值的子字符串复制到s指向的数组中。 这个子字符串包含从位置pos开始的len字符。该函数不会在复制内容的末尾添加空字符。

// 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;
}
//Output:
//buffer contains: string

3.string::find:在字符串中查找内容。在字符串中搜索由其参数指定的序列的第一次出现。当指定pos时,搜索仅包括位置pos处或之后的字符,忽略包括pos之前的字符在内的任何可能的事件。注意,与成员find_first_of不同,只要有一个以上的字符被搜索,仅仅这些字符中的一个匹配是不够的,但是整个序列必须匹配。返回值:第一场比赛的第一个字符的位置。如果没有找到匹配,函数返回string :: npos。

// 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 << '\n';

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

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

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

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

  return 0;
//Output
//first 'needle' found at: 14
//second 'needle' found at: 44
//'haystack' also found at: 30
//Period found at: 51
//There are two prepositions in this haystack with needles
}

4.string::substr:生成子字符串。返回一个新构造的字符串对象,其值初始化为此对象的子字符串的副本。子字符串是从字符位置pos开始的对象的一部分,并且跨越了len字符(或者直到字符串的末尾,以先到者为准)。

// 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 返回pos类型size_t

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

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

  return 0;
//Output:
//think live in details.
}

5.string::compare:比较字符串。将字符串对象(或子字符串)的值与其参数指定的字符序列进行比较。被比较的字符串是字符串对象的值或者 - 如果使用的签名具有pos和len参数 - 在字符位置pos处开始的子字符串,并且跨越len字符。该字符串与比较字符串进行比较,该比较字符串由传递给该函数的其他参数确定。

// comparing apples with apples
#include <iostream>
#include <string>

int main ()
{
  std::string str1 ("green apple");
  std::string str2 ("red apple");

  if (str1.compare(str2) != 0)         //!=0成立
    std::cout << str1 << " is not " << str2 << '\n';

  if (str1.compare(6,5,"apple") == 0)       //==0成立
    std::cout << "still, " << str1 << " is an apple\n";

  if (str2.compare(str2.size()-5,5,"apple") == 0)    //==0成立
    std::cout << "and " << str2 << " is also an apple\n";

  if (str1.compare(6,5,str2,4,5) == 0)   //==0成立
    std::cout << "therefore, both are apples\n";

  return 0;
}

6.string::find_ first_ of:在字符串中查找字符。在字符串中搜索与其参数中指定的任何字符匹配的第一个字符。当指定pos时,搜索仅包括位置pos或之后的字符,忽略pos之前的任何可能的事件。请注意,对于序列中的一个字符来说,就足够了(不是全部)。 请参阅string :: find以查找与整个序列匹配的函数。

// string::find_first_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main ()
{
  std::string str ("Please, replace the vowels in this sentence by asterisks.");
  std::size_t found = str.find_first_of("aeiou");
  //下面的循环实现了找到str中,”aeiou“中所有字符:'a''e''i''o''u',并将其都替换为'* '
  while (found!=std::string::npos)
  {
    str[found]='*';
    found=str.find_first_of("aeiou",found+1);
  }

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

  return 0;
//Output:
//Pl**s*, r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.
}

7.string::find_ first_ not_of:查找字符串中没有字符。在字符串中搜索与其参数中指定的任何字符不匹配的第一个字符。指定pos时,搜索仅包含位置pos或之后的字符,忽略该字符之前的任何可能的事件。

// string::find_first_not_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main ()
{
  std::string str ("look for non-alphabetic characters...");

  std::size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");

  //下面的代码就是实现找到str中非小写字母的字符,即'-',并返回'-'的位置。
  if (found!=std::string::npos)
  {
    std::cout << "The first non-alphabetic character is " << str[found];
    std::cout << " at position " << found << '\n';
  }

  return 0;
//Output:
//The first non-alphabetic character is - at position 12
}

8.string::find_ last_of:从结尾查找字符串。在字符串中搜索与其参数中指定的任何字符匹配的最后一个字符。当pos被指定时,搜索只包含位置pos之前或之前的字符,忽略pos之后的任何可能的事件。

// string::find_last_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

void SplitFilename (const std::string& str)
{
  std::cout << "Splitting: " << str << '\n';
  std::size_t found = str.find_last_of("/\\");   //在str中搜索与"/\\"中任一个字符匹配的最后一个字符。
  std::cout << " path: " << str.substr(0,found) << '\n';   //pos就是匹配到的位置。0~pos
  std::cout << " file: " << str.substr(found+1) << '\n';   //pos~string结束
}

int main ()
{
  std::string str1 ("/usr/bin/man");
  std::string str2 ("c:\\windows\\winhelp.exe");

  SplitFilename (str1);
  SplitFilename (str2);

  return 0;
\\Output
\\Splitting: /usr/bin/man
\\ path: /usr/bin
\\ file: man
\\Splitting: c:\windows\winhelp.exe
\\ path: c:\windows
\\ file: winhelp.exe
}

这里介绍了好几个string中有关find的函数,其实还可以参考其他有关于find函数的解释:C++string中用于查找的find系列函数浅析

string::npos

size_ t的最大值。npos是一个静态成员常量值,对于size_ t类型的元素具有最大的可能值。这个值在字符串的成员函数中用作len(或sublen)参数的值时,意思是“直到字符串结尾”。作为返回值,通常用来表示不匹配。这个常量被定义为-1,这是因为size_ t是一个无符号整型,它是这种类型最大的可表示值。

string-Non-member function overloads

这里写图片描述

1.operator>> (string)与operator<< (string):示例代码如下:

// extract to string
#include <iostream>
#include <string>

main ()
{
  std::string name;

  std::cout << "Please, enter your name: ";
  std::cin >> name;
  std::cout << "Hello, " << name << "!\n";

  return 0;
}

2.getline (string):示例代码如下:

// extract to string
#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;
}
  • 79
    点赞
  • 436
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
引用中提到了std::string的初始化方法,可以通过以下两种方法进行初始化: 1.1. 初始化方法一:使用花括号{}以及要赋给字符串的值来声明和初始化std::string变量。 例如: ```cpp std::string str{"这是一个字符串"}; ``` 1.2. 初始化方法二:使用花括号{}以及要赋给字符串的值和要截取的长度来声明和初始化std::string变量。 例如: ```cpp std::string str2{"abcde", 3}; ``` 这样会将字符串"abcde"中的前3个字符赋给str2。 引用中提到了使用std::to_string()来将数字转换为std::string的方法。例如: ```cpp int i = 123; std::string str = std::to_string(i); ``` 这样会将整数123转换为字符串"123"并赋给str。 引用提到了在C++17中,std::to_string()可能会因为依赖于本地环境而导致多个线程同时调用时出现序列化结果的问题。为了解决这个问题,C++17引入了一个高性能且不依赖于本地环境的替代函数std::to_chars()。 至于std::string string8和string16,请问您是指的什么具体内容呢?<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [C/C++笔记:std::string(一)](https://blog.csdn.net/Nine_Yao/article/details/123706441)[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^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [c++11总结18——std::to_string](https://blog.csdn.net/www_dong/article/details/118162447)[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^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值