1. Computing & Technology

Discuss in my forum

C# Programming Tutorial - About Strings and Chars

By , About.com Guide

9 of 10

Yet More C# String Functions and Methods

Join and Split

Join takes a String array and a separator string and produces a single string with one separator between each element in the array. Split does the opposite, splitting a string made up of several elements separated by a separator.
 string commatext = "alpha,bravo,charlie";
 string[] words = commatext.Split(',') ;
 string dashed = string.Join("---", words) ;
 Console.WriteLine("Dashed join is {0}", dashed) ;
 
This takes the alpha,bravo, charlie string splits it into the words string aray then rejoins all three words with dashes using join. Note that split is an instance method whereas join is a static.

PadLeft and PadRight

These two functions pad a string to the left or right with to the specified length. By default the character is a space but an overload lets you specify an alternative char. Just don't forget that these methods return a new string. Just doing
 x.PadRight(x.Length + 10) ;
 
will NOT add ten spaces to x (assuming x is a string). You have to do
 string y = x.PadRight(x.Length + 10) ;
 
Example ex5 shows PadRight being used in an unusual way to create a string of 60 spaces and an asterisk. Both of these statements will do this.
 string s1 = "".PadRight(60) + '*';
 string s2 = String.Empty.PadRight(60) + '*';
 

StartsWith and EndsWith

Both methods return true or false if a string starts or ends with the specified string. Using the example above
 if (s1.StartsWith(" "))
    Console.WriteLine("S1 starts with spaces") ;
 

On the next page - Formatting Strings

©2012 About.com. All rights reserved.

A part of The New York Times Company.