1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Programming Tutorial - About Strings and Chars

By David Bolton, About.com

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

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Yet More C# String Functions and Methods

©2009 About.com, a part of The New York Times Company.

All rights reserved.