程序竞赛中对字符串的容易处理方法

程序竞赛中对字符串的简单处理方法

substr()函数用法:

substr(起始位置,长度)


#include<string>
#include<iostream>
using namespace std;
main()
{
	string s("12345asdf");
	string a=s.substr(0,4);    //获得字符串s中 从第0位开始的长度为4的字符串
	cout<<a<<endl;
}

输出结果为:
1234

assign()函数:
函数以下列方式赋值:


用str为字符串赋值, 
用str的开始num个字符为字符串赋值, 
用str的子串为字符串赋值,子串以index索引开始,长度为len 
用num个字符ch为字符串赋值. 
例如以下代码:


#include<string>
#include<iostream>
using namespace std;
main()
{
    string str1, str2 = "War and Peace";
    str1.assign( str2, 4, 3 );        //str2 字符串的第4个字符位置开始赋值给str1,长度为3个字符
    cout << str1 << endl;
}


输出结果为:
and

赋值(assign) 
语法: 
basic_string &assign( const basic_string &str );
basic_string &assign( const char *str );
basic_string &assign( const char *str, size_type num );
basic_string &assign( const basic_string &str, size_type index, size_type len );

basic_string &assign( size_type num, char ch );


/*以上为转载..我只是做了一点格式转换*/

STL map :

http://www.cplusplus.com/reference/map/map/map/

以上C++对map类的文档

map 是一个模板类...用二叉堆对有序数对进行一个排序 ,所以每次查询的复杂度为 log(n);


其定义方式有多种比如 

map<int ,string > m ;

map<string ,int > m;

map<int ,int> m;

map<string , string > m;


int main()
{
	string a = "sad";
	string b = "I am sad";
	map<string,string>m;
	string i = m[a];
	if(i=="")
		cout<<"yes"<<endl;
	m[a] = b;
	cout<<m[a]<<endl;
	return 0;
}


输出结果为:

yes

I am sad


一般ACM中用上面的这种用法...比较简单易懂 

可以做为一个字符串的引索

注意如果没有引索值的话是 空字符串 或者 空值 (也许是0,有兴趣可以自己研究一下)

sstream 中的 stringstream()

这个就有点强大了...比substring 还要好用一点


    string str,sub[105];
    getline(cin,str);    
    stringstream s(str);  
    int cnt=0;  
    while(s>>sub[cnt++]){}  

用上面的方法能把str 分解为单词储存在sub[]里面

记住加 #include<sstream>


trie 和 后缀数组的 实现方法我估计这个月会写一下 包括之前没写的KMP 拓展KMP AC自动机 都会稍微接触一下...


加油!