Aishu
Aishu

Reputation: 1320

Java - String conversion

I need to change the order of my string to the Expected value. And also the ',' should get match according to my expected.

String actual = "10684 ANNA MARIE DR, GLEN ALLEN, VA, APT 111, 23060";
String expected = "10684 ANNA MARIE DR, APT 111, GLEN ALLEN, VA 23060";

So that, I can assert the result like this

Assert.assertEquals(actual,expected);

Any help would be greatly appreciated.

Upvotes: 0

Views: 118

Answers (6)

VNT
VNT

Reputation: 974

String actualArray[] = actual.split(",");
int i = 0;

String finalStr = actualArray[i] +","+actualArray[i+3]+","+actualArray[i+1]+","+actualArray[i+2]+actualArray[i+4];
System.out.println(finalStr);

Upvotes: 0

LppEdd
LppEdd

Reputation: 21134

Unlike others suggested, that is splitting by ,, arrays aren't going to be equal.

VA and 23060 will result in two different elements, while in the expected String they are a single element.

A clarification from OP is needed.

Upvotes: 0

Matt
Matt

Reputation: 1308

You can always do it in that a little stupid way:

String actual = "10684 ANNA MARIE DR, GLEN ALLEN, VA, APT 111, 23060";
String[] arr = actual.split(", ");
String result = arr[0] + ", " + arr[3] + ", " + arr[1] + ", " + arr[2] + " " + arr[4];

Upvotes: 1

Raman Sahasi
Raman Sahasi

Reputation: 31851

You can split them and sort the array and then check whether they're equal or not.

String actual = "10684 ANNA MARIE DR, GLEN ALLEN, VA, APT 111, 23060";
String expected = "10684 ANNA MARIE DR, APT 111, GLEN ALLEN, VA 23060";

String arr1[] = actual.split(", ");
String arr2[] = expected.split(", ");

Arrays.sort(arr1);
Arrays.sort(arr2);

Assert.assertArrayEquals( arr1, arr2 );

Upvotes: 1

Spasoje Petronijević
Spasoje Petronijević

Reputation: 1598

You should replace that String with Address class and then easily compare addresses. In Effective Java book you can find chapter where they say that String is not good to use to replace some other structure(and obviously you have address structure here).

Upvotes: 0

Reimeus
Reimeus

Reputation: 159784

Split the strings based on ,, sort the resulting arrays, then use Assert.assertArrayEquals to compare the arrays

Upvotes: 1

Related Questions