Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

java - How to remove the last separator in toString()

I am combining two matrices:

matrixA =

719.0 501.0 -75.0
501.0 508.0 -62.0
-75.0 -62.0 10.0

matrixB =

-19.0 -19.0 -19.0 -19.0 -19.0 -19.0 -19.0 -19.0 -19.0 -19.0
-20.0 -20.0 -20.0 -20.0 -20.0 -20.0 -20.0 -20.0 -20.0 -20.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0

matrixA#matrixB- combines using # and

the row is separated using , and

element separated using |

My toString code is:

public String toString() {
        String separator = "|";
            StringBuffer result = new StringBuffer();

        for (int k = 0; k < keys.length; k++) {
                 for(int l = 0; l < keys[k].length; l++){
                result.append(keys[k][l]);
                result.append(separator);
            }
           result.setLength(result.length() - separator.length());
            // add a line break.
            result.append(",");
        }
       result.append("#");
        for (int i = 0; i < values.length; i++) {
           for(int j = 0; j < values[i].length; j++){
                result.append(values[i][j]);
                result.append(separator);
            }
            // remove  separator
            result.setLength(result.length() - separator.length());
            // add a line break.
            result.append(",");
        }
      return result.toString();
    }

and my result is:

719.0|501.0|-75.0,501.0|508.0|-62.0,-75.0|-62.0|10.0,#-19.0|-19.0|-19.0|-19.0|-19.0|-19.0|-19.0|-19.0|-19.0|-19.0,-20.0|-20.0|-20.0|-20.0|-20.0|-20.0|-20.0|-20.0|-20.0|-20.0,0.0|0.0|0.0|0.0|0.0|0.0|0.0|0.0|0.0|0.0,

How to remove the last separator?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could simply remove it by getting a substring without the last element.

return result.substring(0, result.length() - 1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...