Notes from C++ Primer

Operations

Operations of string support lots of operations of sequential container.

  • string s;          define a new empty string object, named s.
  • string s(cp);    define a new string object, initialized by a C-style string pointed by cp.
  • string s(s2);    define a new string object initialized by the copy of s2.
  • is >> s;          read a string splited by space from input stream is, write into s.
  • os << s;         output the s into output stream os.
  • getline(is, s)    get a line of string from input stream is, output into s.
  • s1 + s2           concatenate string s1 and string s2.
  • s1 += s2        concatenate string s2 at the end of string s1.

As the operation of string is almost the same as container, many executions of vector can be replaced like codes below:

string s("Hiya!");
string::iterator iter = s.begin();
while(iter != s.end())
cout << *iter++ << endl; // postfix increment: print old value

Operations only for string

There're three base operations supported by string type but container type.

  • substr function, return the sub-string of current string object.
  • append and replace function, modify string object.
  • a series of find function, which is used to find string object.

Operations of sub-string:

  • s.substr(pos, n)    return a substring of s, from position pos with length n in s.
  • s.substr(pos)        return a substring of s, from position pos to the end of s.
  • s.substr()             return a copy of s.

1. substr

We can pass the beginning position pos of ing substring and a counter n which determines the length of substring to function substr to finish returning substring.

string s("hello world");

// return substring of 5 characters starting at position 6
string s2 = s.substr(6, 5); // s2 = world

An alternative way is:

// return substring from position 6 to the end of s
string s3 = s.substr(6); // s3 = world

2. append and replace

append function offers an shortcut to insert string at the end of string:

string s("C++ Primer");		// initialize s to "C++ Primer"
s.append(" 3rd Ed."); // s == "C++ Primer 3rd Ed." // equivalent to s.append(" 3rd Ed.")
s.insert(s.size(), " 3rd ED.");

replace function is a shortcut of deleting some characters and then inserting other contents:

// starting at position 11, erase 3 characters and then insert "4th"
s.replace(11, 3, "4th"); // s == "C++ Primer 4th Ed." // equivalent way to replace "3rd" by "4th"
s.erase(11, 3); // s == "C++ Primer Ed."
s.insert(11, "4th"); // s == "C++ Primer 4th Ed."

Also, we don't need to require the length of inserting string is the same as the length of deleting string. Thus we can replace longer or shorter string:

s.replace(11, 3, "Fourth");		// s == "C++ Primer Fourth Ed."

3. find operations of string

string class offers 6 kinds of serarch function. They all return a string::size_type type value indicating the position of match, or return a special value string::npos indicating fail. string class define npos as a value larger than any validate index of string.

  • s.find(args)                      find the first position match with args in s.
  • s.rfind(args)                     find the last position match with args in s.
  • s.find_first_of(args)          find the first position match with any character in args in s.
  • s.find_last_of(args)           find the last position match with any character in args in s.
  • s.find_first_not_of(args)    find the first position of character not belong to args in s.
  • s.find_first_not_of(args)    find the first position of character not belong to args in s.

3.1 The simple accurate search is find function.

string name("AnnaBelle");
string::size_type pos1 = name.find("Anna"); // pos1 == 0

By default, find operation is case sensitive:

string lowercase("annabelle");
pos1 = lowercase.find("Anna"); // pos1 == npos

3.2 Find any character

The process of finding any character is more complicated. For example, find the first number in name:

string numerics("0123456789");
string name("r2d2");
string::size_type pos = name.find_first_of(numerics);
cout << "found number at index: " << pos
<< " element is " << name[pos] << endl; // pos == 1

3.3 Find from a predetermined position

We can pass one more parameter pos to the find function, which indicates the beginning position of finding. Generally, this parameter is used to find all the match characters of string s in a loop.

string::size_type pos = 0;

// each trip reset pos to the next instance in name
while((pos = name.find_first_of(numerics, pos)) != string::npos)
{
cout << "found number at index: " << pos
<< " element is " << name[pos] << endl; ++pos; // move to the next character
}

3.4 Find the mismatch position

find_first_not_of function is used to find the first position of mismatch character. For example, finding the first nonnumerical character:

string numbers("0123456789");
string dept("03714p3"); // returns 5, which is the index to the character 'p'
string::size_type pos = dep.find_first_not_of(numerics);

3.5 Reverse finding

We can also find the character from right to left:

string river("Mississippi");
string:size_type first_pos = river.find("is"); // return 1
string:size_type last_pos = river.rfind("is"); // return 4

Attention: find_last function is very likely the find_first function. The only difference is the return of find_last is the last position of first match substring, and the find_first returns the first position of first match match substring.

string Type的更多相关文章

  1. Library string Type

    The string type supports variable-length character strings.The library takes cares of managing memor ...

  2. setLocale(java.util.Locale), setCharacterEncoding(java.lang.String),setContentType(java.lang.String type)

    对于setCharacterEncoding(java.lang.String),这个方法是javax.servlet.ServletRequest和javax.servlet.ServletResp ...

  3. [Cpp primer] Library string Type

    In order to use string type, we need to include the following code #include<string> using std: ...

  4. Library string type(2)——关于String的操作

    关于string的定义,请参阅博文http://blog.csdn.net/larry233/article/details/51483827 string的操作 s.empty() //Return ...

  5. Excel Sheet Column Title (STRING - TYPE CONVERTION)

    QUESTION Given a positive integer, return its corresponding column title as appear in an Excel sheet ...

  6. Redis String Type

    Redis字符串的操作命令和对应的api如下: set [key] [value] JedisAPI:public String set(final String key, final String ...

  7. PythonStudy——字符串类型 String type

    # 1.定义# 需求:你是"好学生" s1 = "你是\"好学生\"" print(s1) # 可以通过引号的嵌套,使内部不同的引号在不转义 ...

  8. entity framework异常 The specified cast from a materialized 'System.Int32' type to the 'System.String' type is not valid

    ROW_NUMBER() OVER (ORDER BY (select Null)) AS Id entity framework 查询中有这句会有异常

  9. (type interface {}) to type string

    go 语言开发中,经常会在函数中碰到使用 insterface{} 作为接收任意参数,但是我们接收的数据经常是需要做类型转换,由于是初学者,因此,初次转换我是直接就 func New(paramete ...

随机推荐

  1. Android向系统日历中添加日程事件

    转自Android向系统日历中添加日程事件 总结 在项目开发中,我们有预约提醒.定时提醒需求时,可以使用系统日历来辅助提醒: 通过向系统日历中写入事件.设置提醒方式(闹钟),实现到时间自动提醒的功能: ...

  2. 《面向对象程序设计(Java)》第四周学习总结

    第一部分 第四章部分理论知识 1.面向对象程序设计概述:java是完全面向对象的,必须熟悉OOP才能编写java程序. 类:由类构造对象的过程称为创建类的实例. 封装:封装是将数据和行为组合在一个包中 ...

  3. leetcode981

    考虑线性的搜索会超时,所以用二叉搜索来解决,代码如下: class TimeMap: def __init__(self): self.ST = dict() def set(self, key: ' ...

  4. synchronized 和reentrantlock的优缺点

    reentrantlock的优点 可以添加多个检控条件, 如果使用synchronized,则只能使用一个. 使用 reentrant locks 可以有多个wait()/notify() 队列. [ ...

  5. java学习--java源文件

    java源文件以“java”为扩展名.源文件的基本组成部分是类(class) 一个源文件中最多只能有一个public类.其他类(如抽象类,default类即省去修饰符的类,接口)的个数不限. 如果源文 ...

  6. java.util.logging jdk日志详解

    jdk自带的日志,结构并不复杂,功能也能满足绝大部分功能.日志写入位置是开放的,只要继承了handler都可以接收日志的写入.handler本身依赖于LogRecord对象,该对象代表一个日志.Han ...

  7. 题目--oil Deposits(油田) 基础DFS(深度搜索)

    上一次基本了解了下BFS,这次又找了个基本的DFS题目来试试水,DFS举个例子来说就是 一种从树的最左端开始一直搜索到最底端,然后回到原端再搜索另一个位置到最底端,也就是称为深度搜索的DFS--dep ...

  8. swift - UIButton按钮有图片是点击高亮 有灰色动画

    取消 高亮的 动画 btn.adjustsImageWhenHighlighted = false btn.layer.removeAllAnimations()

  9. Eclipse常用快捷键(用到想到随时更新)

    原始链接:https://jingyan.baidu.com/article/fedf073771323235ac8977f1.html Shift+Enter在当前行的下一行插入空行(这时鼠标可以在 ...

  10. node.js中express使用cookie-parser 和 cookie-session处理会话

    cookie-parser 中间件用来解析客户端传过来的cookie,cookie-session 中间件用来建立基于cookie的会话session. 一.安装 cookie-parser 和 co ...