1

I'm currently developing a Translator app using yandex API. Due to some reason the translated output comes with many spaces. For a example if I translate "Always faithful" in to Latin, it show result like " Semper fidelis ". So I wanted to remove these spaces and show it like "Semper fidelis" So I wrote below code (this is written with coma because it's clear to see the idea)

 public String modifyString(String tobeModify){ String[] store = tobeModify.split("\\s+"); String output=null; if (store.length == 0){ output = ""; }else if (store.length == 1){ output = store[0]; }else { output = String.join(",", store); } return output; } 

But this product output like ,Semper,fidelis. Also store array has length 2 as I printed it should be empty string. What I want to print the output like "Semper,fidelis" (coma is for demonstration purposes). I can't find out what's wrong here

2
  • A very generic hint for any programmer: if some library function doesn't work as expected - then question your own expectations. For example: read the javadoc for the functions you are using closely. When in doubt, write and run a bunch of tests (preferably unit tests) to make yourself familiar with the function you intend to use. It is always possible to ask other people to share their knowledge on such functions; but typically, you will learn more by simply trying stuff yourself until you master it. This is not true for all languages, but is for java standard library calls. Commented Jun 3, 2016 at 12:13
  • Yeah I tried but I don't read javadocs because I have used split many time but didn't thought it would split a string empty string (using empty string). Well this is for unit testing on client side. Thank you :) Commented Jun 6, 2016 at 3:27

2 Answers 2

3

Use String newStr = tobeModify.trim();

The trim function will cut out the leading spaces and the ending spaces.
Refer: http://www.javatpoint.com/java-string-trim

Sign up to request clarification or add additional context in comments.

1 Comment

then please consider accepting my answer @MenukaIshan
1

If you receive the following output ",Semper,fidelis", it means that your array contains the empty element "".

["", "Semper", "fidelis"] 

You should throw away the empty values from the array:

Arrays.stream(store).filter(s -> !s.isEmpty()).toArray(); 

You may write your method like:

public String modifyString(String s) { return s.trim().replaceAll("\\s+", ", "); } 

3 Comments

you like to write short answers ,you didn't had to complicate stuff so much
@Andrew you are right. I have mentioned that in the question
yes, I do, what about tobeModify.trim().replaceAll("\\s+", ", ")?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.