-1

suppose we have String str = "Hello-Hello1"; How do we split it and compare it to see if it is equal or not?

This is what I wrote, but it does not give me the result.

public static void main(String[] args) {

        String str = "Hello-Hello1";
        
        String [] a = str.split("-");
        
        for(int i=0; i<a.length; i++) {
            System.out.print(a[i]+ " ");
        }

        for(int first =0; first<a.length; first++) {
            for(int second =first+1; second<a.length; second ++) {
                if(a[first].equals(a[second])){
                    System.out.println(a[first]);
                }
            }
        }
         
    }

Sultana
  • 11
  • 3
  • 1
    First, welcome to SO, can you give more information about what you want to split (like split by char "-" or split by space...", what you want to compare (compare the first part with the second part or we will have multiple part after split) ,...... – Dang Nguyen Jul 28 '20 at 03:22
  • @DangNguyen, Thank you, sure can you please check my answer. yes I want to split the string by "-" then it gives me array of string now I want to compare the result – Sultana Jul 28 '20 at 03:27
  • @Sultana - Please give a concrete example for what you are trying to accomplish. For example, for the input "Hello-Hello1" what do you want to the output to be. The more examples the better. Thanks. – Michael Markidis Jul 28 '20 at 03:44
  • @MichaelMarkidis, so I have a string that i need to split it by "-" once we split string the result is an array of string which in my case has two elements {Hello, Hello1} how could we compare these two to check whether they are equal or not. you can check the questio again I post my code in it. – Sultana Jul 28 '20 at 12:37
  • Why not just use `if(a[0].equals(a[1])) {...}`, instead of those 2 `for` loops surrounding the comparison? I think you have made things far more complicated than needed. And also a check, first, to ensure the array has a length of 2. – andrewJames Jul 28 '20 at 18:24

2 Answers2

0

First, you split your string like shown here: How to split a string in Java, then compare them using the equals method: a[0].equals(a[1]);

Haim Lvov
  • 903
  • 2
  • 10
  • 20
0

Thank you all for helping Here is the answer

public class SplitStringAndCompare {
    public static void main(String[] args) {
        String str = "Hello-Hello1";
        
        String [] a = str.split("-");
        
        if(a[0].equals(a[1])) {
            System.out.println(a[0]+ " is equal to " + a[1]);
        } else {
            System.out.println(a[0]+ " is not equal to "+ a[1]);
        }
        
    }
Sultana
  • 11
  • 3