C++ standard library-string

string

  • initialization
string name_1;
string name_2("LiueDeHua");
string name_3(name_2);
string name_4(5, 'l');

// 在C++中这种方法是不太好的,因为会先调用默认的构造函数初始化name, 然后进行赋值
string name = "LiuDeHua";	
  • cin && getline()
/*
* cin 与 getline
*/
// 如果开始出为空白字符,读取并忽略从开始处的所有空白字符(如空格,换行)
// 从第一个有效字符继续读取字符直到遇到空白字符,读取结束
string s;
cin >> s; 
// 循环读取,直到遇到结束符停止, linux中输入Enter+ctrl+D结束读取,在linux/unix中ctrl+D代表false, windows中ctrl+z代表false
while (cin >> s) {
    
    
	cout << s << endl;
}

string strline;
// 读取整行文本, 以换行符为结束符,读取所有输入
getline(cin, strline);
  • size && empty
// string.size() 获取string的大小,值为字符串中字符的数量
string str("Hello”);
// size_type 足够表示string大小,int 容易溢出
// int size = str.size();
string:size_type size = str.size();
cout << "str size, char number is " << size << endl;

if (str.size() == 0);
if (str.empty());
  • +, = , == , < , >
string a("HELLO");
string b("WORLD");
string c;
a += b;	// success
a = a + "endl"; // success
c = "hello " + "world"; // error, 在C++中使用+进行字符拼接时,不可以两边都为字符串字面值
  • Subscript operations are used as lvalues
string str("This is a line text");
for (string::size_type i = 0; i < str.size(); ++i) {
    
    
	str[i] = '^';
}
cout << str << endl;
  • C & C++ character processing functions
#include <ctype.h>	// C header file,  
#include <cctype>	// c++ header file

// isalnum() 检查字符是否为字母或数字
// isalpha() 检查字符是否为字母
// iscntrl() 检查字符是否为控制字符
// isdigit() 检查字符是否为数字
// islower() 检查字符是否为小写字母
// isupper() 检查字符是否为大写字母
// toupper() 将字符转换为大写
// tolower() 将字符转换为小写
// ispunct(char) 判断字符是否为标点符号
string str("This is 1 line text!^_^!");
string upper_str;
string lower_str;
string::size_type alnum_cnt = 0;
string::size_type alpha_cnt = 0;
string::size_type cntrl_cnt = 0;
string::size_type digit_cnt = 0;
string::size_type lower_cnt = 0;
string::size_type upper_cnt = 0;
string::size_type punct_cnt = 0;
for (string::size_type i =0; i < str.size(); i++) {
    
    
	if (isalnum(str[i])
		++alnum_cnt;
	if (isalpna(str[i]) 
		++alpah_cnt;
	if (iscntrl(str[i])
		++cntrl_cnt;
	if (isdigit(str[i])
		++digit_cnt;
	if (islower(str[i))
		++lower_cnt;
	if (isupper(str[i])
		++upper_cnt;		
	if (ispunct(str[i])
		++punct_cnt;	
	upper_str += toupper(str[i);
	lower_str += tolower(str[i]);
}
  • trim
// 去除首尾空格
string s("              H e l l W o r l d           ");
if (!s.empty()) {
    
    
    s.erase(0,s.find_first_not_of(' '));
    s.erase(s.find_last_not_of(' ') + 1);
}
    
// 去除所有空格
int index = 0;
if (!s.empty()) {
    
    
   while( (index = s.find(' ', index)) != string::npos ) {
    
    
        s.erase(index, 1);
    	}
   	}

Guess you like

Origin blog.csdn.net/gripex/article/details/103980157