Several methods of removing superfluous characters at the end of a string

title: Several methods of removing superfluous characters at the end of a string
date: 2018-08-17 22:12:58
tags: [Java, method]
---

When splicing strings, we often find many unwanted characters, which are very annoying. Here are three ways to get rid of annoyance.

//Cyclic generation of json format data
public static String CreateJson() {
        String json="{\"content\":[";
        for(int i=0;i<5;i++) {
            json+="{\"value\":"+i+"},";
        }
        json+="]}";
        return json;
    }
The json format data generated by the above code (with a comma at the end):
{
    "content": [{
        "value": 0
    }, {
        "value": 1
    }, {
        "value": 2
    }, {
        "value": 3
    }, {
        "value": 4
    },]
}

Method 1: If the number of cycles is known, it can be solved by if judgment:

public static String CreateJson() {
        String json="{\"content\":[";
        for(int i=0;i<5;i++) {
            json+="{\"value\":"+i+"}";
             //Knowing the number of cycles, such as a set of arrays, can be handled by knowing the length.
            if(i<4) {
                json+=",";
            }
        }
        json+="]}";
        return json;
    }

Method 2: Use subString to intercept strings:

public static String CreateJson() {
        String json="{\"content\":[";
        for(int i=0;i<5;i++) {
            json+="{\"value\":"+i+"},";
            //subString intercepts the 0th to the last minus one
            json=json.substring(0, json.length()-1);
        }
        json+="]}";
        return json;
    }

Method 3: Convert String type to String Buffer and delete it

public static String CreateJson() {
        String json="{\"content\":[";
        for(int i=0;i<5;i++) {
            json+="{\"value\":"+i+"},";
        }
        json+="]}";
        //Converting String to String Buffer
        StringBuffer buffer = new StringBuffer(json);
        //Delete commas
        buffer.delete(buffer.length()-3, buffer.length()-2);
        //Convert StringBuffer to String
        json = new String(buffer);
        return json;
    }

Summary: Both method 1 and method 2 are commonly used, but personal sense method 2 may be inefficient in dealing with long strings, and method 3 may feel a little troublesome.

Keywords: Java JSON

Added by JsF on Sat, 05 Oct 2019 08:44:35 +0300