This question is for C Sharp (a开发者_开发技巧nd Java maybe :).
When I want to display a message to the console, I want to insert after each "+" a blank space. How can I do this, without inserting manually that blank space?
try this
var text = string.Join(" ", new[] {foo, bar, other });
You can't, really - just put it in explicitly:
Console.WriteLine(foo + " " + bar);
or
System.out.println(foo + " " + bar);
I mean you could write a method with a parameter array / varargs parameter, e.g. (C#)
public void WriteToConsole(params object[] values)
{
string separator = "";
foreach (object value in values)
{
Console.Write(separator);
separator = " ";
Console.Write(value);
}
}
... but personally I wouldn't.
if you're looking for a way to tidy your printing routine try String.Format
e.g.
Console.WriteLine(String.Format("{0} {1}", string1, string2));
In C#:
string.Join(" ", "Foo", "Bar", "Baz");
In Java:
String.join(" ", "Foo", "Bar", "Baz");
Each of these methods permits a variable number of strings to join, and each has various overloads to pass in collections of strings too.
You can replace "+" with "+ ". Something like this:
new String("Foo+Bar").replace("+", "+ ");
Do you mean a concatenation of strings or just a '+' character? In Java, if there are lot of parameters to show within an output string you can use String.format
method like this: String.format("First: %s, second: %s, third: %s etc", param1, param2, param3)
. In my opinion it's more readable than chained concatenation with '+' operator.
In C# you can use String Interpolation as well using the $
special character, which identifies a string literal as an interpolated string
string text1 = "Hello";
string text2 = "World!";
Console.WriteLine($"{text1}, {text2}");
Output
Hello, World!
From Docs
String interpolation provides a more readable and convenient syntax to create formatted strings than a string composite formatting feature.
// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// String interpolation:
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
Both calls produce the same output that is similar to:
Hello, Mark! Today is Wednesday, it's 19:40 now.
Or in Java you can use the printf
variant of System.out
:
System.out.printf("%s %s", foo, bar);
Remember to put in a "\n
" [line feed] at the end, if there are multiple lines to print.
精彩评论