[英]Need to put semicolon at the end of last line
I want to put semicolon only at the end of the second line (or the last line) not the first.我只想在第二行(或最后一行)而不是第一行的末尾放置分号。
Taking three strings in an array: String[] = {"My first string", "My second string", "My last string"};
取数组中的三个字符串: String[] = {"My first string", "My second string", "My last string"};
My current output:我目前的输出:
My first string;
My second string;
My last string;
I need output in the form:我需要以下形式的输出:
My first string My second string My last string;
Try to do something in this way.尝试以这种方式做某事。
String outputString;
for(String str : yourString) {
outputString = outputString + str;
}
outputString = outputString + ";" ;
Other option:其他选择:
There is the Arrays.toString() method, which will convert an array to a string representation of its contents.有 Arrays.toString() 方法,它会将数组转换为其内容的字符串表示形式。 Then you can pass that string to System.out.println or whatever you're using to print it.然后你可以将该字符串传递给 System.out.println 或任何你用来打印它的东西。
For example :例如 :
String newString = Arrays.toString(str).replace(",", " ");
newString = newString.substring(1, newString.length()-1)+";";
Output :输出 :
My first string My second string My last string;我的第一根弦 我的第二根弦 我的最后一根弦;
Try this:尝试这个:
for(int i = 0; i < array.length; i++) {
append(array[i].append((i == array.length-1) ? ";" : ""));
}
Note that the use of ternary operator will check for the last element of the array.请注意,使用三元运算符将检查数组的最后一个元素。 Using this you can control the appending of the a semicolon or a blank使用它,您可以控制分号或空格的附加
Sure you can, with something like:当然可以,例如:
class Test {
public static void main(String[] args) {
String[] sarr = {"My first string", "My second string", "My last string"};
String sep = "";
for (String s: sarr) {
System.out.print (sep + s);
sep = " ";
}
System.out.println(";");
}
}
It simply outputs out each string in the array, preceded by a separator (initially an empty string but a single space after the first array element is output).它只是输出数组中的每个字符串,前面有一个分隔符(最初是一个空字符串,但在输出第一个数组元素之后有一个空格)。
Then, at the end, it outputs the semicolon and newline:然后,最后,它输出分号和换行符:
My first string My second string My last string;
Try below.. it may help试试下面..它可能会有所帮助
String[] string= {"My first string", "My second string", "My last string"};
string[string.length-1]+=";";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.