Working With Strings in C#

In C#, there are many predefined methods for manipulating String and Dates which serve as a tool for solving many problems. We are going to have a program where most of the methods are used to manipulate strings and then go one by one.

String Methods:

  • In First string, we need double quotes in our line but our compiler will get it as a special character so we use a backslash. This is called the escape character. Now the compiler will treat these as normal characters of strings.
  • In the Second string, the output contains a new line due to ‘\n’ which is a new line character.
  • In the Third string, we are starting the string with @ to ensure that compiler will take backslash as a normal character.
  • After that in the Fourth string, we are using Format() method to have a formatted string where 1 and 0 in the curly braces will be replaced by Second and First. In general, the numbers in the curly braces are replaced by the corresponding number of variables passed in a method after the string.
  • Next one is also the same but instead, it has ‘:C’ inside curly braces to convert the value in the currency of the present region. Like that ‘:N’ is used  to separate numbers in the unit system, ‘:P’ is for percentage, ‘#’ is for spacing and brackets

In C# we have some string function which can return substrings of a string and also can change cases, replace or remove substrings. Next block of code in the given example has these methods.

Output:

There are other advanced functions also like Trim(). And strings can be declared as StringBuilder myString = new StringBuilder(). StringBuilder is mutable, means if create string builder object then you can perform any operation like insert, replace or append without creating a new instance for every time it will update string at one place in memory doesn’t create new space in memory.

Leave a Reply

Your email address will not be published. Required fields are marked *