概述
一、何为字符串
在C语言中,一串以'\0'结尾的字符被认为字符串。字符串可以用数组来存放,当然可以用<string>的头文件来直接使用。数组可以直接用字符串来初始化,例如char arr[100] ="happy" 或 char arr[100] ={"happy"}。
二、字符串的输入输出
输入\输出 | 样例 | 特点 |
Scanf | 1. char ch; scanf(%c, &ch); 2. char s[100]; scanf(%s, sh); 以上需要注意是否要有&符号 | 1. scanf不能读入空格' ', 制表符‘\t’, 换行‘\n’ 2. 要读取一句话的话,只能一个单词一个单词读取 |
gets | 1. char s[200]; gets(s); | 1. gets读到换行‘\n’为止 2. gets可以读入空格' ', 制表符‘\t’ 3. 可能需要用getchar()来配合。 |
sscanf | 1. int a, double b; sscanf(ss,"%d%lf" &a, &b) | 1. 读进与指定格式相符合的字符串 |
puts | ||
printf |
三、字符串的操作
1. 初始化: memset函数
2. 获取长度: strlen函数
3. 复制字符串: strcpy函数
4. 连接字符串:strcat函数,当然C++可以直接用“+”就可以
5. 比较字符串:strcmp函数
四、相关算法(KMP算法和BF算法)
参考:http://www.cnblogs.com/dolphin0520/archive/2011/08/24/2151846.html
五、例子
规律如下:
S(1)=1,
S(2)=11,由S(1)从左往右1个1,所以为11;
S(3)=21,由S(2)从左往右2个1所以为21;
S(4)=1211,有S(3)从左往右1个2,1个1,所以为1211;
S(5)=111221,同理1个1,1个2,2个1,所以为111221
S(6)=312211,同理为3个1,2个2,1个1,所以为312211
知道规律了题目就容易解决了!
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 #include <iostream> 2 #include <string> 3 #include <cstring> 4 5 using namespace std; 6 7 int main(){ 8 9 string s="1"; 10 11 int n, len[35]; 12 13 len[0] = 1; 14 for(int i=1; i<=30; i++){ 15 unsigned int j, k=0; 16 string tmp; 17 for(j=1; j<s.length(); j++){ 18 if(s[k] != s[j]){ 19 tmp.push_back(j-k+'0'); 20 tmp.push_back(s[k]); 21 k = j; 22 } 23 } 24 tmp.push_back(j-k+'0'); 25 tmp += s[k]; 26 s = tmp; 27 len[i] = s.length(); 28 } 29 30 while(cin >>n && n){ 31 cout << len[n-1] << endl; 32 } 33 34 return 0; 35 }