简体   繁体   中英

String.join doesn't work as expected

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

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

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+", ", ");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM