Reputation: 421
I have this code which output some value from array, plus -
in new line under value a[i]
Console.Write(a[i] + "\n-");
So it looks like this
a
-
Now i have more of Console.Write(a[i+1] + "\n-");
codes and it outputs like this
a
-b
-c
-d
-
I know why this is the case but how can I return one line up after every new line \n
? So I can get this
abcd
----
Upvotes: 4
Views: 1925
Reputation: 201
Their are two ways.
The first way is mentioned above.The general idea is to print two lines seperately and that gives you the absolutely same result as what you want in a very simple way.
The second way is to set the cusor position using SetCursorPosition(int Left ,int Top) right under the current position and Write('_') and then move the cusor back again.
Upvotes: 1
Reputation: 939
What you are looking for is Console.SetCursorPosition
var baseLine = Console.CursorTop;
char[] a = {'a', 'b', 'c', 'd'};
char[] b = {'A', 'B', 'C', 'D'};
string[] conditions = {"a", "a", "both", "b"}; // Which arrays to show
for (int i = 0; i < a.Length; i++)
{
Console.SetCursorPosition(i, baseLine);
Console.Write(conditions[i] != "b" ? a[i] : '-');
Console.SetCursorPosition(i, baseLine + 1);
Console.Write(conditions[i] != "a" ? b[i] : '-');
}
baseLine
is needed because you don't know in which line you are going to start.
Output:
abc-
--CD
Upvotes: 0
Reputation: 45947
Another approach with Concat
:
char[] a = {'a','b','c','d'};
Console.WriteLine(string.Concat(a));
Console.WriteLine(new string('-',a.Length));
https://dotnetfiddle.net/IZdlX5
Upvotes: 2
Reputation: 493
One liner with Linq:
Console.Write(String.Concat(a) + "\n" + new String('-', a.Length));
Upvotes: 0
Reputation: 218827
You don't "go one line up". You output the first line and then output the second line. So first you'd output your whole a
array, then output a line of hyphens the length of that array. Maybe something like this:
Console.WriteLine(string.Join("", a));
Console.WriteLine(string.Join("", a.Select(_ => "-")));
The first line would join all elements of the a
array into a single string, the second line uses kind of a trick with LINQ to "query" the a
array but return a hyphen instead of anything from that array, then outputs the same way.
Upvotes: 0
Reputation: 156978
You have to output the values first, then the dashes:
Console.WriteLine(string.Join("", a)); // make a string of all values and write a line end
Console.WriteLine(string.Join("", a.Select(v => "-"))); // write the dashes
[Ideone]
Upvotes: 8