How can I insert a blank space ("") when I concatenate a string?

This question is for C Sharp (and Java is possible :).

When I want to display a message in the console, I want to insert a space after each "+". How can I do this without manually inserting empty space?

+6
java c #
source share
7 answers

try it

var text = string.Join(" ", new[] {foo, bar, other }); 
+11
source share

In fact, you cannot just specify:

 Console.WriteLine(foo + " " + bar); 

or

 System.out.println(foo + " " + bar); 

I mean, you can write a method with an array / varargs parameter, for example. (FROM#)

 public void WriteToConsole(params object[] values) { string separator = ""; foreach (object value in values) { Console.Write(separator); separator = " "; Console.Write(value); } } 

... but personally, I would not do that.

+6
source share

if you are looking for a way to streamline your printing procedure, try String.Format for example.

 Console.WriteLine(String.Format("{0} {1}", string1, string2)); 
+5
source share

You can replace "+" with "+". Something like that:

 new String("Foo+Bar").replace("+", "+ "); 
+3
source share

In C # :

 string.Join(" ", "Foo", "Bar", "Baz"); 

In Java :

 string.Join(" ", "Foo", "Bar", "Baz"); 

Each of these methods allows a variable number of rows to be attached, and each of them has different overloads for passing in collections of strings.

+2
source share

Or in Java you can use the printf System.out option:

 System.out.printf("%s %s", foo, bar); 

Remember to add " \n " [line feed] at the end if there are several lines to print. A.

0
source share

Do you mean string concatenation or just the "+" character? In Java, if there are many parameters in the output string, you can use the String.format method as follows: String.format("First: %s, second: %s, third: %s etc", param1, param2, param3) . In my opinion, this is more readable than chain concatenation using the "+" operator.

0
source share

All Articles