22/07/2008

C#: Some useful String Manipulation Functions

String Starts or Ends With Sequence of Characters

This method returns a boolean value if the initial string either starts with or ends with the sought after string (startOrEndsWithTest).

private bool StringStartsOrEndsWith(string initialString,
string startOrEndsWithTest)
{
if (initialString.StartsWith(startOrEndsWithTest)) return true;
int intCheckLen = startOrEndsWithTest.Length;
if (initialString.Length >= intCheckLen)
return (initialString.Substring(initialString.Length -
intCheckLen, intCheckLen) == startOrEndsWithTest);

return false;
}

String Insert Before Search String Method

The following method inserts a string (textToBeInserted) before a search string (insertBeforeText) located in the initial string (initialString).

private string StringInsertBefore(string initialString,
string insertBeforeText, string textToBeInserted)
{
int intPos = initialString.IndexOf(insertBeforeText);
if (intPos == -1) return initialString;
return String.Concat(initialString.Substring(0, intPos),
textToBeInserted,
initialString.Substring(intPos, initialString.Length - (intPos)));
}

String Insert After Search String Method

The following method inserts a string (textToBeInserted) after a search string (insertBeforeText) located in the initial string (initialString).

private string StringInsertAfter(string initialString,
string insertAfterText, string textToBeInserted)
{
int intPos = initialString.IndexOf(insertAfterText);
if (intPos == -1) return initialString;
int insertAfterTextLen = insertAfterText.Length;
return String.Concat(initialString.Substring(0, intPos + insertAfterTextLen),
textToBeInserted,
initialString.Substring(intPos + insertAfterTextLen,
initialString.Length - (intPos + insertAfterTextLen)));
}

No comments: