#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//排序函数
void stringSort(char str[][80], int n);
void stringSort(string str[], int n);
//字符串输入函数
void inputString(char str[][80], int n);
void inputString(string str[], int n);
//字符串输出函数
void printString(char str[][80], int n);
void printString(string str[], int n);
//主函数
int main()
{
char s[5][80];
string s1[5];
//char型存储字符串
inputString(s, 5);
cout << "char型存储的串排序前:" << endl;
printString(s, 5);
stringSort(s, 5);
cout << endl << "char型存储的串排序后:" << endl;
printString(s, 5);
cout << endl << endl;
//string类存储串
inputString(s1, 5);
cout << "string串排序前:" << endl;
printString(s1, 5);
stringSort(s1, 5);
cout << endl << "string串排序后:" << endl;
printString(s1, 5);
cout << endl;
return 0;
}
void stringSort(char str[][80], int n)
{
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (strcmp(str[j], str[j + 1]) > 0)
{
swap(str[j], str[j + 1]);
}
}
}
}
void stringSort(string str[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (str[j] > str[j+1])
{
swap(str[j], str[j + 1]);
}
}
}
}
void inputString(char str[][80], int n)
{
for (int i = 0; i < n; i++)
{
cin >> str[i];
}
}
void inputString(string str[], int n)
{
for (int i = 0; i < n; i++)
{
cin >> str[i];
}
}
void printString(char str[][80], int n)
{
for (int i = 0; i < n; i++)
{
cout << str[i] << " ";
}
}
void printString(string str[], int n)
{
for (int i = 0; i < n; i++)
{
cout << str[i] << " ";
}
}
char数组中字符串的比较需要使用strcmp,但是string只需要>、<直接比较就可以了
char数组中的赋值可以使用①scanf和%s,但是在vs下面运行会一直提示忽略了scanf返回值 ②可以使用strcpy,如下图贴上strcpy的简易用法(我所知道的)
char arr[10]="abcd";
char *p="hello";
strcpy(arr,p);
cout<<arr<<endl;
cout<<p<<endl;
结果:
hello
hello
但我最开始的代码没用这个,直接用了swap库函数,swap详情用法请移步别处
在char的二维数组中,第一个[ x ]代表有x个字符串,第二个[ y ]代表每个字符串最多容纳y个字符。在进行for循环时不用嵌套循环第二个[ ],只需要循环第一个就可以了
以上。
有错误请指出,这只是一次做作业有感,给我自己留下笔记了,很粗糙。