问题
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?
回答1:
Instead of adding separator to the end of the entity(row, element etc.), you can add it to the beginning of the next entity.
For example, for ,
you can do this:-
for (int k = 0; k < keys.length; k++) {
// add a line break.
if (k != 0)
result.append(",");
for(int l = 0; l < keys[k].length; l++){
result.append(keys[k][l]);
result.append(separator);
}
}
回答2:
You could simply remove it by getting a substring without the last element.
return result.substring(0, result.length() - 1);
回答3:
result.toString().replaceAll(",$", "");
回答4:
I believe you should be able to add a if condition to check the value of i/k and add a (,) based on it.
来源:https://stackoverflow.com/questions/19783726/how-to-remove-the-last-separator-in-tostring