In this blog post, we will learn how we can add a tab in string in C#.
There are a lot of places in your code where you would feel the need to add a tab character in C#.
This can be a tab character at the start of a new paragraph or somewhere else.
Add Tab Character In C# Using The \t Character
In C#, we use the \t escape character to add a tab character space in string in C#.
If you use the "\t" escape character once, it adds one tab space in string.
This tab character can be used in a string or just directly passed and concatenated with a string and written to console.
Let's look at a code example to understand this further.
Console.WriteLine("This is a heading"); Console.WriteLine("\tThis is where the new line starts after the initial tab space."); Console.WriteLine("This is another line but this line does not start with a tab space.");
Result:
This is a heading This is where the new line starts after the initial tab space. This is another line but this line does not start with a tab space.
By looking at the above example, you can clearly see that by using the "\t" tab character in a string, we can add a tab character.
This is clearly visible in the result.
In the above example, we are using the "\t" tab escape character directly in Console.Writeline.
Adding Tab Character In C# By Adding Tab Character In String
Let's look at another example in which we use the tab character.
string tabCharacter = "\t"; string heading = "This is a heading"; string line1 = "This is where the new line starts after the initial tab space."; string line2 = "This is another line but this line does not start with a tab space."; string joinStrings = string.Join(Environment.NewLine, heading, tabCharacter + line1, line2); Console.WriteLine(joinStrings);
Result:
This is a heading This is where the new line starts after the initial tab space. This is another line but this line does not start with a tab space.