Home > Backend Development > C#.Net Tutorial > Introduction to the usage of string in c++

Introduction to the usage of string in c++

王林
Release: 2020-05-06 09:58:01
Original
3415 people have browsed it

Introduction to the usage of string in c++

string is included in the string library (not string.h, not .h). It can define a string variable just like defining a character, and the powerful C also has various built-in Function, the basic implementation eliminates the need to hand-write functions, and can also perform lexicographic comparisons and string operations.

1. Bitwise and string operations

For example

string s = "abcdef";
cout << s[0] << endl;
Copy after login

The result should be the output character 'a', and the string type can also be used Directly add another string, for example

string a = "abc", b = "bcd";
a = a + b;
cout << a << endl;
Copy after login

The result should be the output string "abcbcd".

2. Built-in functions

The string type actually includes many functions, such as

string s = "a";
    s.append(2,&#39;b&#39;);//s.append(n,c);在s串后面加入n个c字符(append还有其他用法,详情可百度)
    s.erase(s.begin(),s.begin()+2);//s.erase(l,r);删除某个区间,l,r都为迭代器
    s.erase(it);//删除一个字符,it为迭代器
    s.size();//返回字符串s的长度大小
    s.begin();//返回首位置的迭代器
    s.end();//返回末位置的迭代器
    s.insert(it,ch);//在it位置插入ch字符,it为迭代器
    s.resize(len,c);//把字符串当前大小置为len,并用c填充不足的部分
    s.empty();//判断是否为空串
    s.length();//返回字符串的长度
    s.max_size();//返回当前系统string对象可存放的最大长度
    s.capacity();//返回当前容量
    s.at(k);//返回第k+1个字符(该用法会坚持是否越界)
    s.c_str();//返回C字符串的指针,内容为s串
    s.find(s1);//查找s中是否包含s1,并返回头位置,找不到则返回string::npos
    s.replace(k,x,ch);//从k位置开始,把后面的x个元素替换为ch(还有很多其他用法)
    s.swap(s2);//交换两个string字符串
Copy after login

and string also supports direct comparison of two strings. size (built-in lexicographic comparison).

Of course, in addition to the functions written above, string has many other functions.

Recommended tutorial: c tutorial

The above is the detailed content of Introduction to the usage of string in c++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template