1

I have an array of String like: "11456811193903(admin 2016-03-01 11:16:23) (Sale)", I want to remove " (Sale)" from the array String. How to replace this in an array of Strings?

Original String:
String[] fileName = {"11456811193903(admin 2016-03-01 11:16:23) (Sale)"};

After replacing:
fileName:11456811193903(admin 2016-03-01 11:16:23)
1
  • 4
    despite the fact that the array only contains one variable, which might be just an example, you just have to loop over the array and use the String#replace method, if you simply want to replace a literal. Commented Mar 1, 2016 at 7:19

2 Answers 2

4

Bahramdun's solution works perfectly fine, but if you are a fan of Java 8 streams you might want to use this:

String[] fileName = {...};
fileName = Arrays.stream(fileName)
                 .map(s -> s.replace("(Sale)", ""))
                 .toArray(size -> new String[size]);
Sign up to request clarification or add additional context in comments.

3 Comments

You dont actually need to collect as a list and then convert to Array. A simple way would be: fileName = Arrays.stream(fileName) .map(s -> s.replace("(Sale)", "")).toArray(size -> new String[size]);
It says " Lambda expressions are allowed only at source level 1.8 or above"
@SheenaTyagi yes you have to compile your code with/for Java 8 to use Streams.
2

You can try this: If your array has more than one element, then you can loop over the array as shown below. And if it is only one sentence, then you can directly remove the (Scale) and assign it again to the String fileName

String[] fileName = {"11456811193903(admin 2016-03-01 11:16:23) (Sale)"};
for (int i = 0; i < fileName.length; i++) {
    fileName[i] = fileName[i].replaceAll("\\(Sale\\)", "");
}
System.out.println("fileName = " + Arrays.toString(fileName));

And it is the result:

fileName = [11456811193903(admin 2016-03-01 11:16:23)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.