【问题标题】:Comparing Strings using Split , toCharArray and Equals methods使用 Split 、 toCharArray 和 Equals 方法比较字符串
【发布时间】:2019-04-18 00:54:05
【问题描述】:

我正在尝试比较 2 个字符串。我使用了 split 方法,然后使用了 toCharArray 方法。

毕竟我用过等于,但最后我得到:

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException"

import java.util.Scanner;

public  class LoopsWiederholung {
public static void main (String [] args){

    System.out.print("Enter the first String : ");
    Scanner scan1  =  new Scanner(System.in);
    String s1  = scan1.next();
    s1.toUpperCase();

    System.out.print("Enter the second String : ");
    String s2 = scan1.next();
    s2.toUpperCase();
    String[] s3 = new String[100];
    s3 = s1.split("\\ ");

    String[] s4 = new String[100];
    s4 = s2.split("\\ ");

    for (int i = 0 ; i< 100 ; i++){
       if( s3[i].toCharArray().equals(s4[i].toCharArray())){
           System.out.print(s3[i]);
           }
       }


   }
}

【问题讨论】:

  • 您将字符串与s3[i].toCharArray().equals(s4[i].toCharArray()) 进行比较有什么特殊原因吗?您可以直接将它们与s3[i].equals(s4[i]) 进行比较。
  • @KevinAnderson 我猜是作业
  • 使用 string1.equals(string2) 比较两个字符串是否相等可能会有所帮助
  • 数组不认为自己与其他具有相同内容的数组相等。
  • 我以为@Omar 会是个鬼

标签: java arrays exception indexoutofboundsexception


【解决方案1】:

这么多错误,用cmets找我的代码

    System.out.print("Enter the first String : ");
    Scanner scan1  =  new Scanner(System.in);
    String s1  = scan1.next();
    s1 = s1.toUpperCase();  // Strings are immutable

    System.out.print("Enter the second String : ");
    String s2 = scan1.next();
    s2 = s2.toUpperCase();

    // first check the lengths
    if (s1.length() != s2.length()) {
        System.out.println("not the same");
        return;
    }

    String[] s3 = s1.split(""); // use this pattern

    String[] s4 = s2.split("");

    for (int i = 0 ; i< s3.length ; i++){
        if (s3[i].equals(s4[i]))
           System.out.print(s3[i]);
       }
   }

我认为您要么split 得到Strings 的数组,要么使用toCharArray() 来比较chars

【讨论】:

  • @khelwood 不知道。我猜是作业。当然,所有这些代码都可以很容易地替换为if (s1.equals(s2)) System.out.println ("equal")); 正如我在回答中提到的那样,如果这是作业应该做的,也可以使用 toCharArray() 来比较字符
【解决方案2】:

for 循环从 0 迭代到 99,但它假定该数组中有 99 个元素,因此如果没有,您会看到 ArrayIndexOutOfBoundsException。

一个解决方法可能是改变:

String[] s3 = s1.split("\\ ");

String[] s4 = s2.split("\\ ");

这样for循环就可以改成:

for (int i = 0 ; i< s3.length(); i++){
    if(s3[i].equals(s4[i])){
        System.out.print(s3[i]);
    }
}

正如@Scary Wombat 所说,使用string1.equals(string2) 比较两个字符串比检查字符数组更容易。

【讨论】:

  • 我正在尝试比较 2 个字符串 - 不知道为什么 OP 会像他那样分裂。
  • 我做了你在这里提到的。但它只给出一个单词作为输出。我的意思是我写了 2 个相同的句子,但它只检查第一个单词并打印出来
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多