string和char数组关于字符串的输入输出和排序区别

#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循环时不用嵌套循环第二个[ ],只需要循环第一个就可以了

以上。

有错误请指出,这只是一次做作业有感,给我自己留下笔记了,很粗糙。

 

 

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值