String in C#

Understand String Manipulation

String is an array of individual letters that we can loop through the string variable by accessing each individual element in that array and print it out.

String as an array of Char:

Here I will write about String, Manipulating String, Looping from Left -to-Right(smallest to largest) and Looping from Right-to-Left(Largest to smallest).
I will start with answers to questions to make it more clear:

Question 1:Loop through a given name(Tolulope Ademilua)  and print it out:

           string result ="";
            string names = "Tolulope Ademilua"; 
            for (int i = 0; i <names.Length; i++)
                result += names[i];
            resultLabel.Text = result;
Save and Run:
Output : Tolulope Ademilua.    

Question 2.  Reverse "Tolulope Ademilua" to get  aulimedA epoluloT and print it out

This requires just backward looping through the string.
Solution: Therefore we are going to totally  change the executing loop of the for() statement to run on a downward spiral.

Steps to follow:

  • The loop should start from the string largest index, since we are turning the name from its last index.
  • Decrementing the string index, since i'm taking its printing from the largest index number in the array(an ordered series or arrangement) of the individual letters in the string. 
  • Then print the result.

       Setting up the code this way

            string result ="";
            string names = "Tolulope Ademilua"; 
            for (int i = names.Length; i >=0; i--)
                result += names[i];
            resultLabel.Text = result;

Well this code above we give an  exception of type 'System.IndexOutOfRangeException' occurred  but was not handled in user code, In other to solve this problem we need to always remember that our index is zero-based, Therefore counting from 0-upward. Consequently, an index of an array is -1 less than it's actual element. i.e  Elements : 1 2 3 4 5 6 7 8 9 operate with an index counting from 0 1 2 3 4 5 6 7 8. 
Elements: 1  2  3  4  5  6   7   8   9 
Indexes :   0  1  2  3  4   5   6  7   8 
Therefore the problem of this code  is obvious from the above lines of code inside the for() statement. Where I need to set the names.Length to be -1 less than the real mathematical length which is 17. Now if I  have
then our array will conform with the principle of zero-based which will therefore have index length from 0 to 16.
Save and Run:

Using Split() to split String into a String [ ] Array

Splitting a string into a Sting[ ] array is one of the useful tools in programming. Let's say we need to reverse this name "Tolulope, Ademilua ,Samuel ,John, Precious" to "Precious ,John Samuel ,Ademilua, Tolulope" , as we can see this is a bit different from reversing a string of characters (letters) ofcourse we could approach this problem with the same method we used in solving the previous one but there is one specific method will need to call on our string  and store it to a string array moving its state from it string of char. Before I solve this problem I will illustrate on how the string of char is different from the string[ ] array:

Let start with the given names
string names = "Tolulope, Ademilua, Samuel, John, Precious";  // It has an index from 0 to 41 but its actual elements is 42.
Therefore the above string is treated as a string of Char.
string[ ] names =  { "Tolulope", "Ademilua", "Samuel", "John", "Precious" } ; // has an index of 0 to 4  but its actual elements is 5.

Learn also: Class and Objects(Object-Oriented Programming)

This string[ ] names is treated as a string[ ] array. Therefore here each name takes a whole index number but each individual letters takes in a whole index number in string of characters. Basically what determines a string[ ] at it index counting is this double quotes ("") , so anything inside this quotes is counted as a string with a whole index number. While that of string of char is counted as an index of  each individual letters.
Remember the principle of index is -1 less that its actual element.
Solution to question: 
            string result = "";
            string names = "Tolulope, Ademilua, Samuel, John, Precious";
            string[] split = names.Split(',');
            for (int i = split.Length - 1; i >= 0; i--)
             result += split[i] + ",";
            string removeLastComma = result.Remove(result.Length - 1, 1);
            resultLabel.Text = removeLastComma;
Save and Run:

Review the code

  • Declared an empty string variable result.
  • Declared a string named names that stores the given names.
  • Declared a string of array  that gets our splitted names stored and covert it to an array of string and no more a string of char.
  • I looped through the array with for() statement.
  • Inside the code block of the for statement, I store each printed values with a comma after each name from the array back to the initial declared result
  • I declared a variable to remove the last comma that our result has before sending the final result to resultLabel.Text

Manipulating String

IndexOf()  --- This can be used to get to an index number of a particularly targeted string.
string names = "Tolulope Ademilua";
int index = name.IndexOf("milu");
 resultLabel.Text = "'milu' is at index" + index.ToString();

Save and Run:
'milu' is at index 12

Remove() : This is use to remove  letters or string starting from a selected index:
Example: Remove  "milu" from Ademilua and output "Tolulope Adea"
string names = "Tolulope Ademilua";
int index = name.IndexOf("milu");
 string remove= string.Format("Remove \"milu\" from Ademilua and print {0}", name.Remove(index, name.Length - index));
resultLabel.Text = remove;

Save and Run:
Remove "milu" from Ademilua and print Tolulope Ade

Obviously, our result is yet to complete, I need "Tolulope Adea" and not "Tolulope Ade". Before I fix this I will analyze what this method does.
Basically what this Remove method did was that it asks for the startIndex from where to remove letters from.
I set the index I want with an interger variable named index and I initialized the variable with name.IndexOf(char value=>, in this case, I set it to check the index where "milu" belongs to AND start removing whatever items that start from that index). After that, I call the Length of the string with the name.

Length and subtract the startIndex (Which i declared as Int index)  from the string length, which will remove every value from milu down to the last letter (a) at index 16.  Mathematically It can be read as a name.Remove(13, 17 - 5)), i.e from index 13 start removing values from a string of 17 letters and subtract all the equivalent letters counting down from that index 13, in this case, which is letters "milu" which equivalent to  number  4 +  "a" the last letter which denotes +1 to 4  making it 5. 

Therefore 17-5 = 12 that means our startIndex is not balance logically since our index is -1 less than our element. in this case, 16-4 = 12 will solve this problem.  
Now to fix this problem remember to -1 from the index starting from "milu" to "a"  since we don't want our "a" to be counted: Therefore the final solution will be :  
string names = "Tolulope Ademilua";
int index = name.IndexOf("milu");
string remove= string.Format("Remove \"milu\" from Ademilua and print {0}", name.Remove(index, name.Length - index-1));
resultLabel.Text = remove;
Save and Run:

This means  0 1 2 3 4 5 6 7 8 9 10 11 M I L U 16  -  5 - 1  = = names.Length - index-1

PadLeft () and PadRight()

PadlLeft method adds number of spaces in which characters are added into the left of the string sequence,  and the characters are placed at the padded space. While PadRight does same on the Right side.  Tip: The longer the length of the string the lower the length of the padded characters and the lower the length of the string the longer the padded space could be or but taking the same length.
Example 1:
On a string of 4 characters named "Tolu" add 6 characters to the left.
string name = "Tolu";
string padleft = name.PadLeft(10 , '*');
resultlabel.Text = padleft;
Save and Run:


Review the Code

  • String name is declared and initialized with the value (Tolu).
  • String padleft is declared, and initialized with name and accessor (period) is appended on the name to call our PadLeft method in which this method takes in two arguments, one is  integer and second is character. (note that since our value is of type char, so it has to be enclosed with a single-quotes.
  • resultLabel.Text  takes in the values coming from padleft and output them.

Note: The integer totalWidth input parameter for PadLeft() and PadRight() evaluates the width of the entire string. In this case, if we typed in ‘Tolu’ for the string and pressed OK, we would have 6‘*’ characters preceding it, because totalWidth is equal to 10, and ‘Tolu’ has a length of 4.

Example 2:

On a string of  "Tolu, Ademilua, Samuel, John"  add padleft and padright to their sides with the total length of spaces equaivalent to  18. 

string padright ="";
string name = "Tolu, Ademilua, Samuel, John";
string [ ] convertNameToArray = name.Split( ',');
for(int i=0; i< convertNameToArray.Length; i++)
int padleft = (18- convertNameToArray [i].Length)/2  
string padleft = convertNameToArray[ i].PadLeft(convertNameToArray[i].Length + padleft ,   '*' );
padright += padleft.PadRight(18 , '*') +  <br/>";
resultLabel.Text = padright;

Save and Run:
Example 2 result

1 comment:

Note: only a member of this blog may post a comment.

New Post

New style string formatting in Python

In this section, you will learn the usage of the new style formatting. Learn more here . Python 3 introduced a new way to do string formatti...