算法提高 11-1实现strcmp函数

来源:互联网 发布:ubuntu 安装tftp 编辑:程序博客网 时间:2024/05/21 05:41

问题描述
  自己实现一个比较字符串大小的函数,也即实现strcmp函数。函数:intmyStrcmp(char *s1,char *s2)按照ASCII顺序比较字符串s1与s2。若s1与s2相等返回0,s1>s2返回1,s1
  "A"<"B"
  "a">"A"
  "computer">"compare"
  "hello"<"helloworld"
样例输出
算法提高 <wbr>11-1实现strcmp函数
数据规模和约定
  字符串长度<100。

import java.util.Scanner;//实现strcmp函数public class Main {public static void main(String[] args){// TODO Auto-generated methodstubScanner sc=newScanner(System.in);String s1=sc.next();String s2=sc.next();char a[]=s1.toCharArray();char b[]=s2.toCharArray();int  num=0;if(a.lengthfor(int i=0;iif(a[i]>b[i]){System.out.println("-1");break;}else if(a[i]System.out.println("1");break;}else{num ;}if(num==a.length){System.out.println("-1");}}}if(a.length>b.length){for(int i=0;iif(a[i]>b[i]){System.out.println("-1");break;}else if(a[i]System.out.println("1");break;}else{num ;}if(num==b.length){System.out.println("1");}}}if(a.length==b.length){for(int i=0;iif(a[i]>b[i]){System.out.println("-1");break;}else if(a[i]System.out.println("1");break;}else{num ;}if(num==a.length){System.out.println("0");}}}}}



注:此题是C语言,说用什么指针,当时也懂,用java格式中最笨的方式做出来的,原理还是挺简单的,就是用ASCII码比大小解决的,谁有简单的方式欢迎私信或者评论