5 String Tips Every Code Developer Should Know
These are 5 essential tips for coding in C# about strings.
1# Add Variables To Strings Easier:
Adding ‘$’ to the start of the string would allow you to add ints, floats, doubles and booleans just by writing {} and the variable inside.
Let’s say you have a variable called points, and you want to show the user how many points he has, you can write:
Console.WriteLine($”You got {points} points”);
Instead of writing:
Console.WriteLine(“You got “ + points + “ points”);
2# Add Variables To Strings Easier Part 2:
You can write {} and inside write numbers starting from 0 going up,
After you close the string, you add variables separated by commas.
For example:
int int1 = 12;
bool bool1 = false;
Console.WriteLine(“int 1- {0}, bool 1- {1}.”, int1, bool1);
Instead of:
Console.WriteLine(“int 1- “ + int1 + “, bool 1- “ + bool1 + “.”);
3# Add String To a String:
You can add a string to other strings just like adding numbers:
string string1 = “sentence one, ”;
string string2 = “sentence two”;
string1 += string2;
string1 is now- “sentence one, sentence two”.
4# Convert Char Array To a String:
If you have an array of character you can convert them into a string:
char[] chars = { ‘w’, ‘o’, ‘r’, ‘d’ };
string string1 = new string(chars);
string1 is now- “word”.
5# Repeat a Character:
To repeat the same character, just write the character and the number of times you want it repeated:
string string1 = new string(‘d’, 7);
string1 is now- “ddddddd”.