Monday, 26 November 2012

c sharp classes

Splitting and joining strings



Split takes a sentence and returns an array of words:
string[] words = "The quick brown fox".Split();
foreach (string word in words)
  Console.Write (word + "|");    // The|quick|brown|fox|
By default, Split uses whitespace characters as delimiters;  it’s also overloaded to
accept a params array of char or string delimiters. Split also optionally accepts a
StringSplitOptions  enum, which has an option  to  remove  empty  entries:  this  is
useful when words are separated by several delimiters in a row.



The static Join method does the reverse of Split. It requires a delimiter and string
array:
string[] words = "The quick brown fox".Split();
string together = string.Join (" ", words);      // The quick brown fox
The static Concat method is similar to Join but accepts only a params string array and
applies no separator. Concat is exactly equivalent to the + operator (the compiler, in
fact, translates + to Concat):
string sentence     = string.Concat ("The", " quick", " brown", " fox");
string sameSentence = "The" + " quick" + " brown" + " fox";

No comments:

Post a Comment