算法训练 - 比较字符串 编程实现两个字符串s1和s2的字典序比较。(保证每一个字符串不是另一个的前缀,且长度在100以内)。若s1和s2相等,输出0;若它们不相等,则指出其第一个不同字符的ASCII

问题描述

编程实现两个字符串s1和s2的字典序比较。(保证每一个字符串不是另一个的前缀,且长度在100以内)。若s1和s2相等,输出0;若它们不相等,则指出其第一个不同字符的ASCII码的差值:如果s1>s2,则差值为正;如果s1<s2,则差值为负。
例子
样例输入

java basic
样例输出

8

#include <stdio.h>
int q_cz(char * s1, char * s2 )
{
	while( * s1 == * s2 )
	{
		if(*s1=='\0')
		{
			return 0;
		}
		s1++;
		s2++;
	}
	return * s1 - * s2 ;
} 
int main()
{
	char zf1[128];
	char zf2[128];
	scanf("%s%s", &zf1 , &zf2);
	printf("%d\n",q_cz( zf1 , zf2));
    return 0;
}

运行示例
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个示例的strtype类,实现字符串的连接和比较功能。 ```c++ #include <iostream> #include <cstring> using namespace std; class strtype { private: char* str; // 字符串存储 public: strtype(const char* s = "") { // 构造函数 str = new char[strlen(s) + 1]; strcpy(str, s); } ~strtype() { delete[] str; } // 析构函数 void display() const { cout << str << endl; } // 输出字符串 void concat(const strtype& s2) { // 字符串连接 char* temp = new char[strlen(str) + strlen(s2.str) + 1]; strcpy(temp, str); strcat(temp, s2.str); delete[] str; str = temp; } int compare(const strtype& s2) const { // 字符串比较 return strcmp(str, s2.str); } }; int main() { strtype s1("Hello"), s2("World"); s1.display(); // 输出 Hello s2.display(); // 输出 World s1.concat(s2); s1.display(); // 输出 HelloWorld cout << s1.compare(s2) << endl; // 输出一个负数(s1 小于 s2) return 0; } ``` 在这个示例中,我们定义了一个strtype类,它包含了一个私有成员变量`str`,代表字符串的存储。类中定义了一个构造函数、一个析构函数、一个输出字符串的函数`display`、一个字符串连接的函数`concat`以及一个字符串比较的函数`compare`。其中,字符串连接函数`concat`使用了动态内存分配,实现两个字符串的连接,并将结果存储在调用函数的对象中。字符串比较函数`compare`使用了标准库函数`strcmp`,返回两个字符串字典序差值。 在主函数中,我们定义了两个`strtype`对象`s1`和`s2`,并调用了它们的`display`函数输出。接着,我们调用了`s1`的`concat`函数,将`s2`连接到了`s1`的后面,并输出了结果。最后,我们调用了`s1`的`compare`函数,比较了`s1`和`s2`的大小关系,并输出了结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值