+92 332 4229 857 99ProjectIdeas@Gmail.com

Strings (C#)


Strings
String is a class provided by the .net framework and it comes under namespace ‘System’.
This class contains all the functions related to the strings.
Following are String Class functions with examples:

String.Substring() Function:

For finding a substring in a specified string:

string strOne = "Charm strikes the sight but merit wins the soul";
            string strNew = strOne.Substring(10);
            MessageBox.Show(strNew);

Output:
               Kes the sight but merit wins soul (substring from 10th index to onwards)


Another example:

string strOne = "Charm strikes the sight but merit wins the soul";
string strNew = strOne.Substring(5,9);
            MessageBox.Show(strNew);
      
Output:
   Strikes (because from 5th index to 9th is a word “strikes”)


String.Split() Function:

Split a string from specified characters:

        string strOne = "Charm strikes the sight";
        string[] newStr = strOne.Split(' '); // splitting a string at every space
        string str = null;

        for (int i = 0; i < newStr.Length; i++)
              str += newStr[i]; // concatenates the whole string[] to string

        MessageBox.Show(str);

Output:
                     
           Charmstrikesthesight  (because all spaces are gone due to splitting the string at every space)

String.Insert() Function:

Insert a character at specified location in string:

         string strOne = "Rocks Rum";
         string newStr = strOne.Insert(1, "u");
         MessageBox.Show(newStr);

Output:
                Ruocks Rum (at index 1 ‘u’ is inserted starting from 0th index)

String.IndexOf() Function:

Determining the character is placed at which location:

          string strOne = "rocks Rum";
          int count = strOne.IndexOf('R');
          MessageBox.Show(count);

Output:
                 6 (because ‘R’ is located at index 6 from the start)

String.Contains() Function:

Contains the specified character/string in your string:

          string strOne = "rocks Rum";
          bool result = strOne.Contains('s');
          MessageBox.Show(result);

Output:
                True (Because string contains ‘s’ in it)


String.Remove() Function:

Removes the character from the specified index to end of string:

          string strOne = "Rocks Rum";
                       string newStr = strOne.Remove(2);
          MessageBox.Show(newStr);

Output:
                 Ro (because all next characters are removed)

Another Example:

          string strOne = "Rocks Rum";
                      string newStr = strOne.Remove(1,3);
          MessageBox.Show(newStr);

Output:
                Rs Rum (because from 1st index to 3rd characters are removed)

String.Replace() Function:

Replace a character wherever it finds the same in the string:

    string strOne = "Rocks Rum";
           string newStr = strOne.Replace('R''S');
           MessageBox.Show(newStr);

Output:
              Socks Sum (replacing ‘R’ with ‘S’ wherever it finds the 'S')

String.Copy() Function:

Creates a new instance of String with same value as specified:

    string strOne = "Maverick";
           string newStr = string.Copy(strOne);
           MessageBox.Show(newStr);

 Output:

            Maverick (Because it copies that strOne value to newStr)

See if reference are equals:
             
     MessageBox.Show(object.ReferenceEquals(strOne,newStr).ToString());

 Output:
          
             False (Because both strings have different references)

String.Join() Function:

Concatenates the strings with a separator between them:

    string strOne = "Pakistan";
           string strTwo = "a islamic republic state";
           MessageBox.Show(string.Join(" : ", strOne, strTwo));
           
Output:
        
           Pakistan : a Islamic republic state


String.Concat() Function:

Concatenates two specified instances of String and returns the new string that contains both the concatenated strings:

           string strOne = "Osama";
           string strTwo = "Maverick";
           MessageBox.Show(string.Concat(strOne,strTwo));
   
   Output:
           
                  OsamaMaverick

   If you write this:

    MessageBox.Show(strOne + strTwo);

   Then Output would be the same:
      
    Output:
           
                   OsamaMaverick

Another example:
  
            string strOne = "1";
            string strTwo = "2";
            MessageBox.Show(strOne + strTwo);
   Output:

               12 (because it concatenates and can’t add them together)

 If you write this:
            
            string strOne = "1";
            string strTwo = "2";
           
            // Converting both strings to integer type
            int intToStr = int.Parse(strOne);
            int intToStr2 = int.Parse(strTwo);

            // Add them
            int result = intToStr + intToStr2;

            // Displays the addition result
            MessageBox.Show(result.ToString());
  
   Output:

                 3

String ToUpper() And ToLower() Functions:
       To upper and lower case the specified string:

ToUpper():

           string strOne = "PakisTan";
           MessageBox.Show(strOne.ToUpper());

Output:
           
                  PAKISTAN

ToLower():

           MessageBox.Show(strOne.ToLower());

Output:

                  pakistan
String StartsWith() And EndsWith() Functions:
See the example below how StartsWith() and EndsWith() funtions work:
StartsWith():
  
string s = "rocks Rum";
bool r=s.StartsWith("R",StringComparison.CurrentCultureIgnoreCase);
MessageBox.Show(r.ToString());

Output:

       True (Because string starts with ‘r’ ignoring case)

EndsWith():

bool r=s.EndsWith("m",StringComparison.CurrentCultureIgnoreCase);
MessageBox.Show(r.ToString());

Output:
           
      True (Because string ends with ‘m’ ignoring case)

String.Equals() Function:

Determine whether two specified string objects have same value or not?

     string strOne = "Osama";
     string strTwo = "Maverick";
     MessageBox.Show(string.Equals(strOne, strTwo).ToString());

Output:

       False (Because strOne and strTwo are not equal)

Or we can write:
  
     bool result = string.Equals(strOne, strTwo);
     MessageBox.Show(result.ToString());

Output:

       False (Because strOne and strTwo are not equal)

Reversing a String:

The following code shows you how to convert a string in reverse order:

       string strOne = "Pakistan";
      
    // Converting the string to char array
    char[] arr = strOne.ToCharArray();

    // Now reverse the char array
    Array.Reverse(arr);

   // Display it
    MessageBox.Show(new string(arr));

Output:

        natsikaP

String.Compare() Function:

Compares the two specified string objects and returns integer that indicates their relative position in the sort order:

   string strOne = "Osama";
   string strTwo = "Maverick";
   MessageBox.Show(string.Compare(strOne, strTwo));
    
 Output:
           
          1 (because strOne is smaller than strTwo)

If you write above code like this, then:
     
   string strOne = "Osama";
   string strTwo = "Maverick";
   MessageBox.Show(string.Compare(strTwo, strOne));
    
 Output:
         
          -1 (because strTwo isn’t smaller than strOne)

Another Example:
             
   string strOne = "Osama";
   string strTwo = "Maverick";
   MessageBox.Show(strOne.CompareTo(strTwo));

 Output:

          1 (because strOne is smaller than strTwo)

If code is like this, then:
     
   MessageBox.Show(strTwo.CompareTo(strOne).ToString());
    
 Output:

         -1 (because strTwo isn’t smaller than strOne)

0 comments: