Strings in c# and its Function – Free C sharp tutorials

  • Strings in c# is a collection of characters.
  • In c# the System.String is the datatype that is used to represent the string.
  • String class is used to represent the string.
  • Strings are immutable (i.e) if we declare a string and if at all we want to modify that string we cannot modify.Strings are non modifiable.

Difference between string  and System.String

Both are same.The difference is how you see it. Convention is

  • string is for variables
  • String is for calling other String class methods.

Let’s say we have a simple c# program

Using System:
class Main
{
     Public static void Main() {
              String str = “hello”;
              String str1 = “hello”;
          }
}
  • In the above code snippet we can see that we have created two variables namely str and str1. Now let’s understand this step by step .
  • when we create str variable and assign a value hello to it.let’s see what happens in memory.

Now, when we create  a  variable str and assign a value hello to it,  the following is what happens in memory.

Generally there are two kinds of memory being involved

  •  heap memory
  •  Stack memory

There is something called as string pool available in the heap memory that stores the value “hello”

In the above example us assume that the value hello is stored in the address 308 and the corresponding reference is stored in stack memory and what we mean by reference is the variable name and the address where  the variable is stored in heap memory is available in stack

Thus we look up to the stack for the availability of a variable and if available the corresponding address is  available then we have got to go and fetch it from the heap  memory

Now in our next line of code

  • we have created a new variable str1 and assigning the same value hello to it .

In this case let us see what happens  in memory.

Here when we create a new variable a new memory is not allocated in heap memory instead a reference alone is created in stack that points to the same memory address in heap.What are the problems we face because of this is that now when we want to modify the value in str
(i.e) hello the value in str1  also gets altered  thus the previous value cannot be retained . Thus the strings are immutable.

Ways to overcome this we use what is called as StringBuilder class. By using the StringBuilder class  we can we can make the strings  mutable
(i.e) we can modify the strings.


Difference between  System.String and StringBuilder

The main difference is System.String is immutable and StringBuilder is mutable. Immutable means once created cannot be modified.

  1.   .StringBuilder str1 = new StringBuilder(“abc”);
  2.    StringBuilder str2 = new StringBuilder();
  • The string object str1 is created with an initial size of three characters and str2 is created as an empty string .they can grow dynamically as more characters are added to them.
  • The StringBuilder is a inbuilt class in c# that contains predefined methods and properties.
  • The System.Text namespace contains the StringBuilder class and therefore we must include the using System.Text directive for creating and manipulating mutable strings.
Method  Operation
Append() Appends a string
AppendFormat() Appends a string using specific format
Insert() Inserts a string at specified position
Remove() Removes

StringBuilder s = new StringBuilder(“hello”);     //object creation

Console.WriteLine(“original string is” + s);

  • the above code snippet we have created an object of  StringBuilder class (s) and  we are assigning a value “hello” to it (i.e) the  StringBuilder object s contains the string value hello.
  • Inorder to concatenate we use the ‘+’ symbol in c#.

code to create a string

using System;
public class program
{
   public static void Main()
     {
          System.String name = "harry";
          System.String rollno = "101";
          System.String avg = "84.12";
          Console.WriteLine(" name is" + name);
          Console.WriteLine(" rollno is" + rollno);
          Console.WriteLine(" avg is" + avg);
     }
}

output

       name is harry
       rollno is 101
       avg is 84.12

As we know System.String is a datatype we have to use that in order to declare a string thus in the above code we have created string variable name, roll no and average and we have assigned corresponding values to it following that we have printed the content on the output screen using our output statement.

  • The Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

Different ways to create a string in c#

create a string using constructor in c#

  • The string can take an array of characters.
Using System:
class Main
{
     Public static void Main() {
              char[] arr={'h','a','r','r','y};
              String name=new String(arr);
              Console.WriteLine(name);
          }
}

output

harry

In the above code we have created an character array and we are initializing the values ‘harry’ to itThen we are copping that object of character array to the string object labelled  name,and finally we are printing it as a string.


creating a string from literal in c#

Using System:
class Main
{
     Public static void Main()   {
              String str = “hello”;
              String str1 = “hello”;
          }
}

another way of writing this is

public class program
{
   public static void Main()
    {
        String name = " harry ";
    }
}

This is the most common method of initiating a string.we just have to give the sting within the quotes.


creating a string using concatenation in c#

In order to concatenate a string we a ‘+’ symbol (i.e) inorder to combine data of different datatypes we do that.let’s understand that with a simple example.

using System;
public class program
{     
   public static void Main()      
    {          
           System.String name = "harry";          
           System.String rollno = "101";          
           System.String avg = "84.12";
           Console.WriteLine( name + " " + rollno + " " + avg );
     }
}

output

harry  101  84.12

creating  a string using  ToString method in c#

The ToString method can be applied to any datatype that had to converted to string.If we want to convert any datatype into  a string datatype we have to use the ToString() method.

using System:
class Main
{
     Public static void Main()   {
              String name = “harry”;
              int rollno=101;
              string data=string.Format(name+"is"+rollno.ToString()+"old");
              Console.WriteLine(data);
          }
}

output

harry is 10 years old

Convert string to charArray in c#

The TocharArray method converts string to a stream of characters.

using System;
public class program
{            
   public static void Main()                            
     {
          string name =     "  harry is living in UK ";
          char[]  charArr  =  name. ToCharArray();
          foreach ( char ch in charArr)using System; public class program {                public static 
            {
                 Console.WriteLine(ch);
            }
      }
}

output

h
a
r
r
y
i
s 
l 
i
v
i
n
g
i
n
U
K
  • In the above code we have declared a string variable and converting it to character array to do that we are actually using something called as the ToCharArray() method to convert a string to array and since we are converting it to a character array we have to print it one by one thus we use a foreach loop to print the characters one by one.

Leave a Comment

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