Substring
A substring is any sequence of characters that is contained in a string. We use Substring method when we want to create a new string that is based on original string. Replace method is used when we want to change parts of original string and create new one. IndexOf is used when we want to locate first occurrence of certain substring in string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
string originalString = "Today we will learn Substring method"; //Index of is zero based so first character will be "T". int newIntCreatedWithIndexOf = originalString.IndexOf("o"); //Substring is zero based so sixth character will be "6", and this method will //create new string starting of character "w" including next 7 characters. string newStringCreatedWithSubstring = originalString.Substring(6, 6); //Replace method will replaces all occurrences of a specified substring with a new value(new string) //so try adding expanding originalString to see results. string newStringCreatedWithReplace = originalString.Replace("we", "you"); Console.WriteLine(newIntCreatedWithIndexOf); Console.WriteLine(newStringCreatedWithSubstring); Console.WriteLine(newStringCreatedWithReplace); |
How to create new string using Multiple existing strings?
That process is called concatenation and all it basically does is append one string at the end of another string. In next example we will create 3 string and concatenate them. For this example Gangsta Lorem Ipsum is used.
1 2 3 4 5 6 7 8 9 10 |
string firstString = "Lorizzle ipsum dolizzle sit sheezy, doggy adipiscing elizzle. Yo tellivizzle velit, dope volutpizzle, suscipit quis, stuff vel, brizzle. "; string secondString = "Pellentesque fo shizzle my nizzle crocodizzle. Funky fresh erizzle. Shiz izzle dolizzle dapibus sizzle boom shackalack fizzle. Maurizzle yo mamma nibh shiz turpis. Mammasay mammasa mamma oo sa izzle tortizzle. Pellentesque eleifend rhoncizzle nisi."; string thirdString = "In hizzle habitasse bow wow wow dictumst. Mammasay mammasa mamma oo sa dapibizzle. Curabitur tellizzle urna, pretizzle ass, mattis ac, eleifend vitae, nunc. Gizzle suscipizzle. Integer sempizzle funky fresh sizzle purus."; string finalString = firstString + secondString + " " + thirdString; Console.WriteLine(finalString); |
As you can see new string is created using simple addition. Notice on third operation ” “, we have created a new string with only one blank space. Why? Because when we create new string we have to add it ourselves. Look at the end of first string, you can see that there is empty space at the end, so we did not have to add between firstString and secondString .
That’s all for now regarding string in future we will talk some more about them.
Tomorrow we will talk about reference types so be sure co check in again!