Иван Тонов
Иван Тонов

Reputation: 39

Java - How to remove special char in string array?

I'm having an array of strings (phone numbers) and i need to remove +, which is in front of one of the elements (numbers) since it throws an NumberFormatException when i try to cast it to int.

The elements in array are 0888888888 0888123456 +359886001122 and i have already used .split(" ") in order to separate them. I've also tried .split(" +") in order to remove + from the last one, but this didn't work.

Upvotes: 2

Views: 5922

Answers (3)

minus
minus

Reputation: 2786

Split uses a regular expression, so you can define to include and optional '+' in the split matcher.

String [] result = "0888888888 0888123456 +359886001122".split("\\s[\\+]{0,1}");

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59950

You have to use replaceAll instead of split, for example :

"0888888888 0888123456 +359886001122".replaceAll("\\+", "");

this will show you :

0888888888 0888123456 359886001122
//-------------------^------------

Then if you want to split each number you can use split(" ") like this :

String numbers[] = "0888888888 0888123456 +359886001122".replaceAll("\\+", "").split(" ");
System.out.println(Arrays.toString(numbers));

this will give you :

[0888888888, 0888123456, 359886001122]

EDIT

Or like @shmosel said in comment you ca use replace("+", "")

Upvotes: 9

TheLovelySausage
TheLovelySausage

Reputation: 4094

You can replace it with

var lv_numbers = "0888888888 0888123456 +359886001122".replace('+','');

Upvotes: 0

Related Questions