0

Currently I am trying to remove dash in my string array. The code that I tried below didn't work.

splitTimeStamp[0].replaceAll("[\\s\\-()]", "");
System.out.println(splitTimeStamp[0]);

Got the replaceAll code from another stackoverflow page.

Thanks in advance!

Sujatha Girijala
  • 1,141
  • 8
  • 20
Bob
  • 157
  • 1
  • 11

4 Answers4

10

The method returns a new String. The original one isn't changed.
You need to save the result like this

splitTimeStamp[0] = splitTimeStamp[0].replaceAll("[\\s\\-()]", "");
System.out.println(splitTimeStamp[0]);
Turamarth
  • 2,282
  • 4
  • 25
  • 31
1

Here's a Java8 way of doing it.

String[] result = Arrays.stream(source)
    .map(s -> s.replaceAll("[\\s\\-()]", ""))
    .toArray(String[]::new);

This approach is much more parallel friendly than the imperative approach.

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
0

While working with String class you always need to remember that if String is an immutable class and never change the existing object. so each method of String class always returns the new object which you need to reassign.

The same mistake is done by you. please assign it back while calling the replaceAll as it's can't change the existing one as it's immutable.

Shivang Agarwal
  • 1,825
  • 1
  • 14
  • 19
0

In case you want to replace everything in the array I would like to suggest this solution :

String[] splitTimeStamp = //...some data
Arrays.setAll(splitTimeStamp, index -> splitTimeStamp[index].replaceAll("[\\s\\-()]", ""));
ziMtyth
  • 1,008
  • 16
  • 32