这次去北京理工参加复试,当时的上机题目的第2题是一道字符串有关的题目:
大致的题目是这样的,在一个已有序列中有Eric,Machel,Peter,要求插入
Jhon,以后按照字母顺序显示排好,并且可以多次输入,如果有相同的提示重新输入。
当时的我对string类并不了解,所以用的是链表和动态生成字符串的方式。后来碰到一个考生,他告诉我有string类做非常的方便。于是我就浅显的看看了。
标准C++库字符串类std::string的用法
#include<string>
std::string s1;
std::string s3(s2);
std::string s2("this is a string");
begin 得到指向字符串开头的Iterator
end 得到指向字符串结尾的Iterator
rbegin 得到指向反向字符串开头的Iterator
rend 得到指向反向字符串结尾的Iterator
size 得到字符串的大小
length() 和size函数功能相同
max_size 字符串可能的最大大小
capacity 在不重新分配内存的情况下,字符串可能的大小
empty 判断是否为空
operator[] 取第几个元素,相当于数组
c_str 取得C风格的const char* 字符串
data 取得字符串内容地址
operator= 赋值操作符
reserve 预留空间
swap 交换函数
insert 插入字符
append 追加字符
push_back 追加字符
erase 删除字符串
clear 清空字符容器中所有内容
resize 重新分配空间
assign 和赋值操作符一样
replace 替代
copy 字符串到空间
find 查找,返回基于0的索引号
rfind 反向查找
find_first_of 查找包含子串中的任何字符,返回第一个位置
find_first_not_of 查找不包含子串中的任何字符,返回第一个位置
find_last_of 查找包含子串中的任何字符,返回最后一个位置
find_last_not_of 查找不包含子串中的任何字符,返回最后一个位置
substr(n1,len) 得到字符串从n1开始的长度为len的子串
比较字符串(支持所有的关系运算符)
compare 比较字符串
operator+ 字符串链接
operator+= += 操作符
operator== 判断是否相等
operator!= 判断是否不等于
operator< 判断是否小于
operator>> 从输入流中读入字符串
operator<< 字符串写入输出流
getline 从输入流中读入一行
这样就方便多了,这个程序的核心方法是对字符串排序,而用数组的方式就比较简单,避免出现悬挂指针的情况。
简易版的算法如下:
#include<iostream>
#include<string>
const int Max=50;
using namespace std;
void sort(string student[],int len)//直接插入
排序算法
{
int i,j;
string temp;
for(i=1;i<len;i++)
{
temp=student[i];
for(j=i-1;j>=0&&temp.compare(student[j])<=0;j--) //compare为比较函数类似strcmp()
student[j+1]=student[j];
student[j+1]=temp;
}
}
void main()
{
string student[Max];//string类
int len;
int i;
student[0]="macddfd";
student[1]="jhon";
student[2]="eric";
student[3]="peter";//初始化
for(i=0;i<4;i++)
cout<<student[i].data()<<" ";
cout<<endl;
len=4;
sort(student,len);
for(i=0;i<4;i++)
cout<<student[i].data()<<" ";
cout<<endl;
}