此次为个人练习,若有错误或需改进敬请提出。
要求:
读取一个字符串,字符串可能含有空格,将字符串逆转,原来的字符串与逆转后字符串相同,输出0,原字符串小于逆转后字符串输出-1,大于逆转后字符串输出1。例如输入 hello,逆转后的字符串为 olleh,因为hello 小于 olleh,所以输出-1。
拓展知识:
str系列字符串操作函数
str系列字符串操作函数主要包括strlen、strcpy、strcmp、strcat等等。其中,strlen函数用于统计字符串的长度,strcpy函数用于将某个字符串赋值到字符数组中,strcmp函数用于比较两个字符串的大小,strcat函数用于将两个字符串连接到一起。注意,这些函数的使用需要引用<string.h>。它们的使用方法如下:
#include <stdio.h>
#include <string.h>
int main()
{
char c[20] = "helloworld";
printf("数组c内字符串的长度=%d\n", strlen(c));
char d[20];
strcpy(d, "study");//复制
//char* strcopy(char* to,const char *from);有const修饰代表可以放一个字符串常量
puts(d);
//看strcmp,两个字符串进行比较是比较对象字符位置的ascii码值
int ret = strcmp("how", "hello");
printf("字符how与字符hello比较后的结果=%d\n", ret);//当how大于hello时输出得值大于0,当how小于hello时输出的值小于0
printf("两个字符串比较后的结果=%d\n", strcmp("hello", "hello"));//当两个字符串的值相等时输出的值为0
//看strcat,是拼接两个字符串,且目标数组要容纳拼接的字符串
strcat(c, d);//将数组c与数组d拼接
puts(c);//输出拼接后的字符串
return 0;
}
因此,通过str系列字符串操作函数,我们可以写出此题的代码。
代码如下:
#include <stdio.h>
#include <string.h>
int main() {
char a[20];
char b[20];
int len;
//int strcmp(const char* a, const char* b);
gets(a);
len = strlen(a);//读取数组a的长度
for (int i = 0; i < len; i++)
{
b[i] = a[len - i - 1];//将a数组的下标存的数据赋值给逆转后b数组的下标
}
b[len] = '\0';//在b数组中,数据结束后添加结束符
if (strcmp(a, b) > 0)//判断原字符串是否大于逆转后的字符串
{
printf("1");
}
else if (strcmp(a, b) < 0)//判断原字符串是否小于逆转后的字符串
{
printf("-1");
}
else
{
printf("0");//原字符串与逆转后的字符串相同
}
}
运行结果:
当输入“hello”时,输出结果应为“-1”:
hello
-1
当输入“cba”时,输出结果应为“1”:
cba
1
当输入“aba”时,输出结果应为“0”:
aba
0
版权声明:本文为m0_51171889原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。