C# removing substring from end of string
Solution 1:
string[] remove = { "a", "am", "p", "pm" };
string inputText = "blalahpm";
foreach (string item in remove)
if (inputText.EndsWith(item))
{
inputText = inputText.Substring(0, inputText.LastIndexOf(item));
break; //only allow one match at most
}
Solution 2:
foreach (string suffix in remove)
{
if (yourString.EndsWith(suffix))
{
yourString = yourString.Remove(yourString.Length - suffix.Length);
break;
}
}
Solution 3:
I think that BrokenGlass's solution is a good one, but personally I would prefer to create three separate methods allowing the user to trim only the start, end or both.
If these bothers were going to be used a lot, I would create them in a helper class and/or as extension methods; http://msdn.microsoft.com/en-gb/library/vstudio/bb383977.aspx
public string TrimStart(string inputText, string value, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase)
{
if (!string.IsNullOrEmpty(value))
{
while (!string.IsNullOrEmpty(inputText) && inputText.StartsWith(value, comparisonType))
{
inputText = inputText.Substring(value.Length - 1);
}
}
return inputText;
}
public string TrimEnd(string inputText, string value, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase)
{
if (!string.IsNullOrEmpty(value))
{
while (!string.IsNullOrEmpty(inputText) && inputText.EndsWith(value, comparisonType))
{
inputText = inputText.Substring(0, (inputText.Length - value.Length));
}
}
return inputText;
}
public string Trim(string inputText, string value, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase)
{
return TrimStart(TrimEnd(inputText, value, comparisonType), value, comparisonType);
}
With these methods we can modify the code for looping through the array containing the strings to be trimmed.
var content = "08:00 AM";
var removeList = new [] { "a", "am", "p", "pm" };
for (var i = 0; i < removeList.length; i++)
{
content = TrimEnd(content, removeList[i]);
}
NOTE: This code could be optimized further, but will work as it is with a good speed.
Solution 4:
Based on your edit, consider using the built-in DateTime.TryParse or DateTime.Parse methods followed by a String.Format. Here's a link to a good resource on formatting strings as well.