C ++ eighth week course notes: String

Note: The syllabus see https://www.cnblogs.com/inchbyinch/p/12398921.html

1 string class

string is an important part of the C ++ Standard Library, mainly for string processing. string class itself defines a number of convenient functions, while C ++ library of algorithms for string also has good support, and has a good interface between the string and the string also c language. Here are some common actions string object list.

  • The main initialization operation, access, assignment, concatenation, comparison, exchange, add or delete search changes, interaction with the strings C, interact with the flow.
  • CPP's official website a more complete example: http://www.cplusplus.com/reference/string/basic_string/
  • The string class is a template class: typedef basic_string <char> string
  • Using the string class to include the header file <string>

1.1 string object initialization

//默认初始化
string s; //s是一个空串
//使用字符串字面值初始化
string s1="hello world";  //拷贝初始化
string s2("hello world");  //直接初始化
//使用其他字符串初始化
string s2=s1; //拷贝初始化,s1是string类对象
string s2(s1); //直接初始化,s1是string类对象
//使用单个字符初始化
string s(10, 'a'); //直接初始化,s的内容是aaaaaaaaaa

//下面是错误的初始化方法
string error1 = 'c'; // 错
string error2('u'); // 错
string error3 = 22; // 错
string error4(8); // 错
//可以将字符赋值给string对象
string s; s = 'n'; //可以

1.2 Access

//获取长度
s.length();
s.size();

//访问元素
s[i];  //不会做范围检查
s.at[i]; //会做范围检查

//获取string迭代器,通过迭代器访问
for(std::string::iterator it=str.begin(); it!=str.end(); ++it)
    std::cout << *it;
std::cout << '\n';

1.3 assignment, connection, comparison, exchange

//赋值方式1:=
//赋值方式2:assign函数,将string对象,或char*字符串(或部分),或指定字符赋给s2
string base("The quick brown fox jumps over a lazy dog.");
string s1, s2;
s1 = "hello";
s1 = 'a';
s1 = base;
s2.assign(base);
s2.assign(base, 1, 5); //从base中下标为1的字符开始复制5个字符给s2
s2.assign(base.begin()+16, base.end()-12);
s2.assign("pangrams are cool");  
s2.assign("pangrams are cool", 7);  // "pangram"
s2.assign(10, '*');

//string连接方式1:+
//string连接方式2:append
string s1("good "), s2("morning! ");
s1 += s2;
s1.append(s2);
s2.append(s1, 3, s1.size()); //从s1下标3开始,复制s1.size()个字符
//如果字符串内没有足够字符,则复制到字符串最后一个字符

//比较方式1: >,  >=,  <,  <=,  ==,  != 返回值为bool类型
//比较方式2:成员函数compare,返回值int:若主体s1大则为正,若小则为负,若等于则为0
string s1("hello"),s2("hello"),s3("hell");
cout << (s1 > s3) << endl; //1
cout << s1.compare(s2) << endl; //0
cout << s1.compare(s3) << endl; //1
cout << s3.compare(s1) << endl; //-1

//swap函数交换string
string s1("hello world"), s2("really");
s1.swap(s2); //成员函数
swap(s1, s2); //全局函数

1.4 additions and deletions to change search

//成员函数substr获取子串
string s1("hello world"), s2;
s2 = s1.substr(4,5);  //下标4开始5个字符

//查找string对象中子串,find()或rfind()
//下例中find()从前向后查找"lo"第一次出现的地方,若找到,返回"lo"开始的位置,
//即'l'所在的位置下标。否则返回string::npos(string中定义的静态常量)
string s1("hello world");
s1.find("lo");  //3
s1.find("ll",3); //4294967295  从下标3处开始查找
s1.rfind("ll"); //2  rfind()从后向前查找,用法和find()相同

//查找string对象中字符
//find_first_of(),find_last_of(),find_first_not_of(),find_last_not_of()
//下例中find_first_of从前向后查找"abcde"中任何一个字符第一次出现的地方
//而find_first_not_of是从前向后查找不在"abcde"中的字母第一次出现的地方
//如果找到则返回找到字母的位置,如果找不到,返回string::npos
string s1("hello world");
s1.find_first_of("abcde");  //1
s1.find_last_of("abcde");  //10
s1.find_first_not_of("abcde"); //0
s1.find_last_not_of("abcde");  //9

//删除erase(), 插入insert(), 替换replace()
s1.erase(5,s1.length()); //自下标5开始删除,可通过下标和迭代器均可定位
s1.insert(5,s2); // 将s2插入s1下标5的位置
s1.insert(2,s2,5,3); //将s2中下标5开始的3个字符插入s1下标2的位置
s1.replace(2,3,"haha"); //将s1中下标2开始的3个字符换成"haha"
s1.replace(2,3,"haha",1,2); //将s1中下标2开始的3个字符换成"haha"中下标1开始的2个字符

1.5 interaction with C-style strings

  • Seamlessly into a C string string object, there are three ways;
  • cout can print directly string C ((const) char * name or array type), without the printf;
  • string objects can () member function into a C string through c_str, const char * return type;
//C风格字符串转为string
const char *s = "Hello world!";
string str1(s);
string str2 = s;
string str3("haha");
str3 = s;

//s1.c_str()返回s1内部的const char* 类型字符串,且该字符串以‘\0’结尾。
string s1("hello world");
const char* p = s1.c_str();
cout << p << endl;  

//copy(),将string复制为char* 字符串,返回复制的字符个数
char buffer[20];
string s1("Test string...");
length = s1.copy(buffer,6,5); //复制长度为6,从下标5开始(与前不同)
buffer[length]='\0';

1.6 interacting with the flow

//string支持流读取运算符
string stringObject;
cin >> stringObject;

//string支持全局getline函数
string s;
getline(cin, s);
//getline和stringstream搭配用于split
string a, b, c, d; 
string lines="adfa;asdfasd;fasdf;ccc";  
stringstream line(lines);  //可以直接初始化
getline(line, a, 'f'); 
getline(line, b, ';'); 
getline(line, c, ';'); 
getline(line, d);   //默认以换行符作为delim

2 stringstream

  • <Sstream> library defines three types: istringstream, ostringstream and the stringstream, are used for input, output, and input and output operations string stream.
  • It is used internally string object instead of an array of characters, so to avoid the risk of buffer overflow. Also it can automatically infer the type, not because of incompatible formats and error.
  • stringstream action 1: generally used for data conversion. Compared conversion c library, it is more secure, automatic and direct.
  • 2 stringstream effect: combined with getline, the string can be used for segmentation.
  • Reference 1 , Reference 2

note:

  • stringstream can be easily used for data conversion, to call attention to each conversion Clear ();
  • clear way is cleared ss the state (such as error, etc.), empty the contents need to use .str ( "") method (actually a replacement if the need to continue with the conversion ss, still have to call clear empty state.);
  • May be utilized ostringstream time into each of the need to convert the string variable, using oss.str () extracted string; string to be converted by using an istringstream constructed, and then turn into respective variable-time (stringstream recommended instead.).
//示例1:利用stringstream,基本数据类型与string互转
int main(){
    int a1 = 56, a2 = 0, a3=0;
    double b1 = 65.123, b2 = 0.0, b3=0.0;
    stringstream ss;  //头文件是sstream

    ss << a1 << " " << b1;  //将基本类型转为string
    cout << "1. " << ss.str() << endl; //1. 56 65.123
    ss >> a2 >> b2; //注:ss中数据应以空格作为分隔
    cout << "2. " << a2 << "---" << b2 << endl; //2. 56---65.123

    ss.clear(); //每一次转换之后都必须调用clear()成员函数清空状态
    //ss.str(""); //可以清空原数据
    ss << b1 << " " << a1;
    cout << "3. " << ss.str() << endl; //3. 56 65.12365.123 56
    ss >> b3 >> a3;
    cout << "4. " << ss.str() << endl; //4. 56 65.12365.123 56
    cout << "5. " << a3 << "---" << b3 << endl; //5. 56---65.123
    return 0;
}


//示例2:利用ostringstream和istringstream进行string与基本类型的互转
int main(){
    int a=1, b=3, a1, b1;
    double c=2.4, d=3.4, c1, d1;
    //一次性读入需要转换成string的各个变量,并保存至string
    ostringstream oss;
    oss << a << " " << b << " " << c << " " << d;
    cout << oss.str() << endl;
    string s = oss.str();
    //利用待转换的string来构造istringstream,然后一次性转成各个变量
    istringstream iss(s);
    iss >> a1 >> b1 >> c1 >> d1;
    cout << iss.str() << endl;
    cout << a1 << " " << b1 << " " << c1 << " " << d1 << endl;
    return 0;
}

trap:

  • ostringstream.str () Returns a string of temporary objects, according to the regular writing should my_string = ostringstream.str () will return the value in time to save, not available ostringstream.str (). c_str ().
  • c_str () returns a pointer of type char * const temporary, if need their own space to save the available content.
  • Reference 1 , Reference 2

3 string-related knowledge

3.1 Some understand

Three distinguished string header files, cstring, string.h

  • string.h something C standard library, there strcpy, memset other functions;
  • For compatibility C C ++, a .h file to set up a shell, with the addition of C, corresponding to a .h file header;
  • On average, a C ++ library old version with ".h" extension libraries, such as string.h, in the standard library has a new standard without the ".h" extension headers (such as cstring) to corresponding to the difference between the latter except for some improvements, as well as the latter point is all the stuff into the "std" namespace, such as calling strlen function, you need to write std :: strlen (yourstr) job;
  • If you are using C ++, then please use cstring, if you are using a C Please string.h;
  • C ++ header file is the string defined std :: string file is used, the string class header file, belongs to the category STL

cstring / string.h header file used function

  • strlen, strcpy, strcat, strcmp
  • memcpy, memset, strtok

STL sort function sort mechanism:

  • Cmp comparison parameter as a function, with two arguments, if it is true, then meet the requirements;
  • Thus, in the comparison function, if the return a <b, compared to ASC, if return a> b, was descending;

Method string segmentation 3.2

  • Method 1: Using string flow; (requires that separate spaces)
  • Method 2: using the string getline function and the global flow; (see example 1.6)
  • Method 3: Use the cstring std :: strtok () function.
#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int main(){
    //目的是将一个string对象按照分隔符分割成几个子串对象
    //通过C风格的strtok函数进行分割 
    //char * strtok(char* str, const char* delimiters);
    //由于strtok函数需要传入C风格的字符串,且会破坏字符串结构,故复制原string对象内容
    string s = "hello,  big  - world.";
    string str1, str2, str3;
    char a[100] = {0};
    std::strcpy(a, s.c_str()); //c_str()函数返回const char*类型
    cout << a << endl; //输出hello,  big  - world.

    str1 = std::strtok(a, " ,-.");
    str2 = std::strtok(NULL, " ,-.");
    str3 = std::strtok(NULL, " ,-.");

    cout << a << endl; //输出hello
    cout << str1 << "-" << str2 << "-" << str3; //输出hello-big-world
    return 0;
}

3.3 into a digital string parsing method

  • Method 1: Using string flow, find () function positioning;
  • Method 2: Using regular expressions, functions, or C scanf;
  • Method 3: Use the cstdlib std :: strtod () function.
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class Complex{
private:
    double r, i;
public:
    Complex(){};
    Complex(const char* p){
        char a[20];
        char* pEnd;
        std::strcpy(a, p);
        r = std::strtod(a, &pEnd);
        i = std::strtod(pEnd+1, NULL);
    }
    void Print() {
        cout << r << "+" << i << "i" << endl;
    }
};

int main(){
    Complex a;
    a = "3+4i"; a.Print();
    a = "5+6i"; a.Print();
    return 0;
}

Guess you like

Origin www.cnblogs.com/inchbyinch/p/12398540.html