When put together the string, the end of several methods remove redundant character


title: When piecing together a string method to remove a few extra characters at the end of
DATE: 2018-08-17 22:12:58
Tags: [the Java, method]
---

In the string concatenation, we often find that many, unwanted characters, people it is a worry, these are summarized below three ways you can get rid of trouble.

//循环生成json格式数据
public static String CreateJson() {
        String json="{\"content\":[";
        for(int i=0;i<5;i++) {
            json+="{\"value\":"+i+"},";
        }
        json+="]}";
        return json;
    }
The above code generation json format data (last more than a comma):
{
    "content": [{
        "value": 0
    }, {
        "value": 1
    }, {
        "value": 2
    }, {
        "value": 3
    }, {
        "value": 4
    },]
}

Method a: If a known number of cycles, can be solved by determining if:

public static String CreateJson() {
        String json="{\"content\":[";
        for(int i=0;i<5;i++) {
            json+="{\"value\":"+i+"}";
             //以知循环的次数,如是数组集合,知道长度就能处理
            if(i<4) {
                json+=",";
            }
        }
        json+="]}";
        return json;
    }

Option two: subString string taken:

public static String CreateJson() {
        String json="{\"content\":[";
        for(int i=0;i<5;i++) {
            json+="{\"value\":"+i+"},";
            //subString截取第0个至最后减一
            json=json.substring(0, json.length()-1);
        }
        json+="]}";
        return json;
    }

Method three: the String type to StringBuffer, then delete

public static String CreateJson() {
        String json="{\"content\":[";
        for(int i=0;i<5;i++) {
            json+="{\"value\":"+i+"},";
        }
        json+="]}";
        //将String转换为StringBuffer
        StringBuffer buffer = new StringBuffer(json);
        //删除逗号
        buffer.delete(buffer.length()-3, buffer.length()-2);
        //再将StringBuffer转换为String
        json = new String(buffer);
        return json;
    }

Summary: Method One and Method Two are still relatively common, but personally feel second method may be inefficient when dealing with long strings, Method three feel a little trouble.

Guess you like

Origin www.cnblogs.com/flytree/p/11622642.html