字符串
前两天遇到了一道题叫数字反转
思路: 第一反应是惯性思维代入套路。
其实应该把它转化为字符串然后反转(这道题题目我就没仔细看。。写的就是反转)
过程: 写的时候也遇到了很多困难,比如string t;没有初始化t字符串导致无输出;比如i=length,这样导致读取错误,还有i>0导致读取不到字符串第一位;还误写了双重循环导致输出4444333322221111等等。
发现:
- 定义一个空字符串需要定义成 string t="";
- 字符串的增加用append,注意:append使用时若添加多个相同字符需写出添加几个。
如:t.append(2,“a”); 向t后面添加2个a字符。
代码如下:
#define LLMAX 9223372036854775807
using namespace std;
typedef long long ll;
typedef int Node;
#include <iostream>
#include <stdio.h>
#include <string>
int main() {
string s;
cin>>s;
string t="";
for(int i=s.length()-1; i>=0; i--)
t.append(1,s[i]);
cout<<t;
}
知识点
关于string的知识:
append:
1.将一个字符串连接到另一个字符串尾:
string a="hello ";string b=“world!”;
a.append(b);
a=“hello world!”
2.将一个字符串一部分连接到另一个字符串尾:
string a=“hello “;string b=“world hello”;
a.append(b,5);//将b的前五个字符连接到当前字符串结尾
a=“hello world”;
3.将一个字符串结尾添加多个字符:
string a=“hello”;
a.eppend(3,”!”);
a=“hello!!!”;
其他知识点
字符串从第0个开始,从length-1结束,最后一个为空白符。
string、char和char[]的区别:
string是以’\0’结尾的字符串,是一个容器被封装好了的。
char是一个指向字符串数组的指针,无法存储字符串,只可以修改指向,不可以修改指向内容。
char[]定义的是一个字符数组。