在java不敏感的情况下使用循环比较两个字符串?

时间:2014-05-12 19:52:53

标签: java loops

编写一个程序来读取两个字符串并打印“Equal”如果它们是相同的不区分大小写。例如:

  • 输入:代码
    • 输出:等于
  • 输入:Masr Masry
    • 输出:不等于
  • 输入:埃及埃及
    • 输出:等于

注意:您应该使用循环。不要使用某种现有方法来检查相等性。

我尝试了这个代码并且使用了5次以上:(

import java.util.Scanner;
public class equal {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in=new Scanner(System.in);
        String st1=in.nextLine();
        String st2=in.nextLine();
        int len1=st1.length();
        int len2=st2.length();
        int y=1;
        if(len1==len2){
            char ch1=st1.charAt(0);
            char ch2=st2.charAt(0);
            int con1=ch1 , con2=ch2;
            if(con1==con2){
                for(int x=1;x<len1;x++){
                    char Ch1=st1.charAt(x);
                    char Ch2=st2.charAt(x);
                    if(Ch1==Ch2){
                        y++;
                    }
                }
            }
        }
        if(y==len1){
            System.out.println("Equal");
        }else if(y!=len1){
            System.out.println("Not Equal");
        }
    }
}

2 个答案:

答案 0 :(得分:3)

选项1:

正如用户ZouZou所说,你可以轻松使用:

char ch1=Character.toLowerCase(st1.charAt(x));

选项2:

但是,如果要避免使用选项1,可以使用switch/case语句(或if/else-if)语句创建自己的方法。您接受一个字符并返回小写版本(如果存在)。否则,只需返回给定的当前字符。

public static char charToLowerCase(char ch){
    switch (ch) {
        case 'A': return 'a'';
        case 'B': return 'b';
        //etc.  write rest of cases
        default:  return ch;
    }
}

然后在你的主循环中:

char ch1=charToLowerCase(st1.charAt(x));

选项3:

选项2是一个简单的解决方案,并不是最有效的,但它很容易理解。它仍然非常适用于此任务。如果您想通过操纵字符的ASCII值来更改字符,请查看此answer和此answer

char toLowerCase(char c){
    if(c>=97 && c<=122)
        return (char) (c-32);
    else
        return c;
}

注意 :此示例仅处理ASCII而不是Unicode!

答案 1 :(得分:0)

检查这个..可能不是一个完美的..但应该有助于你的事业(我绝不会喜欢这样做)

import java.util.Scanner;    
public class Equal {    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String st1 = in.nextLine();
        String st2 = in.nextLine();
        int len1 = st1.length();
        int len2 = st2.length();
        int y = 0;
        if (len1 == len2) {
            for (int x = 0; x < len1; x++) {
                int Ch1 = st1.charAt(x);
                int Ch2 = st2.charAt(x);    
                if (Ch1 >= 65 && Ch1 <= 90) {
                    Ch1 = Ch1 + 32;
                }
                if (Ch2 >= 65 && Ch2 <= 90) {
                    Ch2 = Ch2 + 32;
                }    
                if (Ch1 == Ch2) {
                    y++;
                } else {
                    break;
                }
            }
        } else {
            System.out.println("Not Equal");
        }

        if (y == len1) {
            System.out.println("Equal");
        } else {
            System.out.println("Not Equal");
        }
    }
}
相关问题