Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C#
Article

String Helpers

Rate me:
Please Sign up or sign in to vote.
4.40/5 (25 votes)
15 Jun 20055 min read 108.4K   700   66   23
A small set of helper methods for string manipulation.

Introduction

For almost all my applications, I end up having to do some sort of string manipulation. The String class doesn't support easy string manipulation. The only methods it provides that are of any use for parsing a string are IndexOf, Substring, and Split. Substring is very useful, but it takes integers, so you have to apply IndexOf first to obtain the index of a character inside the string. The result is messy code and a lot of error checking. I've designed the class presented in this article to improve the readability of your code and to define specific behaviors when IndexOf returns -1.

The methods

All of the methods in the StringHelpers class are static methods. The methods are:

  • LeftOf (two overloads)
  • RightOf (two overloads)
  • LeftOfRightmostOf
  • RightOfRightmostOf
  • Between
  • Count
  • Rightmost

LeftOf

Returns the string to the left of the first occurrence of [c] in the [source] string.

Parameters

  • source string,
  • character to find in the source string.

Behavior

Returns a string of all characters to the left of the search character. If the character cannot be found in the source string, the entire string is returned. The rationale here is that the entire string is scanned for the search character, and, not being found, the method returns all the characters scanned.

Implementation

C#
public static string LeftOf(string src, char c)
{
  string ret=src;
  int idx=src.IndexOf(c);
  if (idx != -1)
  {
    ret=src.Substring(0, idx);
  }
  return ret;
}

LeftOf [n]

Returns the string to the left of the [nth] occurrence of [c] in the [source] string.

Parameters

  • source string,
  • character [c] to find in the source string,
  • the nth instance of c to find.

Behavior

Returns a string of all characters to the left of the nth occurrence of the search character. If the character cannot be found in the source string, the entire string is returned. The rationale here is that the entire string is scanned for the search character, and, not being found, the method returns all the characters scanned.

Implementation

C#
public static string LeftOf(string src, char c, int n)
{
  string ret=src;
  int idx=-1;
  while (n > 0)
  {
    idx=src.IndexOf(c, idx+1);
    if (idx==-1)
    {
      break;
    }
  }
  if (idx != -1)
  {
    ret=src.Substring(0, idx);
  }
  return ret;
}

RightOf

Returns the string to the right of the first occurrence of [c] in the [source] string.

Parameters

  • source string,
  • character to find in the source string.

Behavior

Returns a string of all characters to the right of the search character. If the character cannot be found in the source string, an empty string is returned. The rationale here is that the entire string is scanned for the search character, but until the search character is found, these characters are ignored. Therefore, if the search character is not found, the method returns an empty string.

Implementation

C#
public static string RightOf(string src, char c)
{
  string ret=String.Empty;
  int idx=src.IndexOf(c);
  if (idx != -1)
  {
    ret=src.Substring(idx+1);
  }
  return ret;
}

RightOf [n]

Returns the string to the right of the [nth] occurrence of [c] in the [source] string.

Parameters

  • source string,
  • character to find in the source string,
  • the nth instance of [c] to find.

Behavior

Returns a string of all characters to the right of the nth occurrence of the search character. If the character cannot be found in the source string, an empty string is returned. The rationale here is that the entire string is scanned for the search character, but until the search character is found, these characters are ignored. Therefore, if the search character is not found, the method returns an empty string.

Implementation

C#
public static string RightOf(string src, char c, int n)
{
  string ret=String.Empty;
  int idx=-1;
  while (n > 0)
  {
    idx=src.IndexOf(c, idx+1);
    if (idx==-1)
    {
      break;
    }
    --n;
  }

  if (idx != -1)
  {
    ret=src.Substring(idx+1);
  }

  return ret; 
}

LeftOfRightmostOf

Returns the string to the left of the rightmost occurrence of the search character.

Parameters

  • source string,
  • character to find in the source string.

Behavior

Returns a string of all characters to the left of the rightmost occurrence of the search character. If the character cannot be found in the source string, the entire string is returned. The rationale here is that the entire string is scanned for the search character, and, not being found, the method returns all the characters scanned.

Implementation

C#
public static string LeftOfRightmostOf(string src, char c)
{
  string ret=src;
  int idx=src.LastIndexOf(c);
  if (idx != -1)
  {
    ret=src.Substring(0, idx);
  }
  return ret;
}

RightOfRightmostOf

Returns the string to the right of the rightmost occurrence of the search character.

Parameters

  • source string,
  • character to find in the source string.

Behavior

Returns a string of all characters to the right of the rightmost occurrence of the search character. If the character cannot be found in the source string, an empty string is returned. The rationale here is that the entire string is scanned for the search character, but until the search character is found, these characters are ignored. Therefore, if the search character is not found, the method returns an empty string.

Implementation

C#
public static string RightOfRightmostOf(string src, char c)
{
  string ret=String.Empty;
  int idx=src.LastIndexOf(c);
  if (idx != -1)
  {
    ret=src.Substring(idx+1);
  }
  return ret;
}

Between

Returns the string between and exclusive of two search characters.

Parameters

  • The source string.
  • The character to find that demarks the start of the substring, exclusive of the search character.
  • The character to find that demarks the end of the substring, exclusive of the search character.

Behavior

Returns the string that is between the two specified search characters. The returned string excludes the search characters. If the starting character is not found, an empty string is returned. If the ending character is not found after the starting character, an empty string is returned.

Implementation

C#
public static string Between(string src, char start, char end)
{
  string ret=String.Empty;
  int idxStart=src.IndexOf(start);
  if (idxStart != -1)
  {
    ++idxStart;
    int idxEnd=src.IndexOf(end, idxStart);
    if (idxEnd != -1)
    {
      ret=src.Substring(idxStart, idxEnd-idxStart);
    }
  }
  return ret;
}

Count

Returns the number of occurrences of the specified character in the source string.

Parameters

  • The source string.
  • The character of which to count occurrences.

Behavior

Returns 0 if no occurrences of the search character are found in the source string.

Implementation

C#
public static int Count(string src, char find)
{
  int ret=0;
  foreach(char s in src)
  {
    if (s==find)
    {
      ++ret;
    }
  }
  return ret;
}

Rightmost

Returns the rightmost character in the source string.

Parameters

  • The source string.

Behavior

Returns '\0' if the string is empty.

Implementation

C#
public static char Rightmost(string src)
{
  char c='\0';
  if (src.Length>0)
  {
    c=src[src.Length-1];
  }
  return c;
}

Unit tests

There are 17 unit tests provided, using the Advanced Unit Test (AUT) test runner, downloadable here.

Conclusion

You can see that each of these methods is very simple and very short. For more complicated string parsing, I would suggest the Regex class. But for most of my needs, this class works quite well, improving code readability.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect Interacx
United States United States
Blog: https://marcclifton.wordpress.com/
Home Page: http://www.marcclifton.com
Research: http://www.higherorderprogramming.com/
GitHub: https://github.com/cliftonm

All my life I have been passionate about architecture / software design, as this is the cornerstone to a maintainable and extensible application. As such, I have enjoyed exploring some crazy ideas and discovering that they are not so crazy after all. I also love writing about my ideas and seeing the community response. As a consultant, I've enjoyed working in a wide range of industries such as aerospace, boatyard management, remote sensing, emergency services / data management, and casino operations. I've done a variety of pro-bono work non-profit organizations related to nature conservancy, drug recovery and women's health.

Comments and Discussions

 
QuestionSad. Licensee is GNU. Pin
warlockd 202110-Jan-24 11:08
warlockd 202110-Jan-24 11:08 
GeneralMy vote of 5 Pin
vnmatt1-Dec-10 19:54
vnmatt1-Dec-10 19:54 
GeneralRe: My vote of 5 Pin
Marc Clifton2-Dec-10 2:03
mvaMarc Clifton2-Dec-10 2:03 
Questionerror in leftofn function? Pin
cookster6129-Aug-08 0:23
cookster6129-Aug-08 0:23 
AnswerRe: error in leftofn function? Pin
Marc Clifton29-Aug-08 3:28
mvaMarc Clifton29-Aug-08 3:28 
GeneralExtension Methods Pin
Philip Laureano29-Jan-08 13:15
Philip Laureano29-Jan-08 13:15 
GeneralRe: Extension Methods Pin
Marc Clifton29-Jan-08 13:56
mvaMarc Clifton29-Jan-08 13:56 
GeneralThanks Pin
J J S14-Sep-07 4:39
J J S14-Sep-07 4:39 
GeneralBetween Pin
mycsharpcorner3-Apr-07 4:20
mycsharpcorner3-Apr-07 4:20 
GeneralVery good idea Pin
cbolz21-Nov-06 9:59
cbolz21-Nov-06 9:59 
GeneralMore ... Pin
Erlend Robaye10-Jan-06 21:17
Erlend Robaye10-Jan-06 21:17 
GeneralFree methods Pin
Nemanja Trifunovic16-Jun-05 3:31
Nemanja Trifunovic16-Jun-05 3:31 
GeneralRe: Free methods Pin
Marc Clifton16-Jun-05 4:15
mvaMarc Clifton16-Jun-05 4:15 
GeneralRe: Free methods Pin
User 19428920-Jun-05 4:04
User 19428920-Jun-05 4:04 
GeneralExplaination of the reasons/usage missing. Pin
Uwe Keim16-Jun-05 2:12
sitebuilderUwe Keim16-Jun-05 2:12 
GeneralRe: Explaination of the reasons/usage missing. Pin
Marc Clifton16-Jun-05 4:14
mvaMarc Clifton16-Jun-05 4:14 
GeneralRe: Explaination of the reasons/usage missing. Pin
Uwe Keim16-Jun-05 4:29
sitebuilderUwe Keim16-Jun-05 4:29 
GeneralRe: Explaination of the reasons/usage missing. Pin
Marc Clifton16-Jun-05 4:50
mvaMarc Clifton16-Jun-05 4:50 
GeneralRe: Explaination of the reasons/usage missing. Pin
Uwe Keim16-Jun-05 5:04
sitebuilderUwe Keim16-Jun-05 5:04 
GeneralVery Innovative Idea Pin
Gaurang Desai15-Jun-05 19:17
Gaurang Desai15-Jun-05 19:17 
GeneralNice observations Pin
Rei Miyasaka15-Jun-05 15:03
Rei Miyasaka15-Jun-05 15:03 
GeneralRe: Nice observations Pin
AntoineAubry16-Jun-05 2:59
AntoineAubry16-Jun-05 2:59 
GeneralRe: Nice observations Pin
Rei Miyasaka16-Jun-05 10:34
Rei Miyasaka16-Jun-05 10:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.