C# removing substring from end of string

C#StringTextbox

C# Problem Overview


I have an array of strings:

string[] remove = { "a", "am", "p", "pm" };

And I have a textbox that a user enters text into. If they type any string in the remove array at the end of the text in the textbox, it should be removed. What is the easiest way to do this?

EDIT To clarify, I'm making a time parser. When you give the function a string, it does its best to parse it into this format: 08:14pm I have a textbox to test it. When the focus leaves the textbox, I need to get the text without the am/pm/a/p suffix so I can parse the number only segment.

C# Solutions


Solution 1 - C#

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 - C#

foreach (string suffix in remove)
{
    if (yourString.EndsWith(suffix))
    {
        yourString = yourString.Remove(yourString.Length - suffix.Length);
        break;
    }
}

Solution 3 - C#

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 - C#

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.

Solution 5 - C#

Sounds like a good place for regex.

using System.Text.RegularExpressions;

public bool IsValidTime(string thetime)
{
  Regex checktime = new Regex(@"^(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})$");

  return checktime.IsMatch(thetime);
} 

Assuming you want time in the format xx:xx

Solution 6 - C#

var output = (from x in remove
      where input.EndsWith(x)
     select input.Substring(0, input.Length - x.Length)).FirstOrDefault() ?? input;

Solution 7 - C#

You can probably use DateTime as your primary type then.

Use DateTime.TryParse to read the time the user enters. And use DateTime.ToString to reformat the time using whatever format you need.

Solution 8 - C#

char[] remove = { 'a', 'p', 'm' };
string s = "8:14pm";

s = s.TrimEnd(remove);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEntityView Question on Stackoverflow
Solution 1 - C#BrokenGlassView Answer on Stackoverflow
Solution 2 - C#LukeHView Answer on Stackoverflow
Solution 3 - C#Shane YuView Answer on Stackoverflow
Solution 4 - C#Metro SmurfView Answer on Stackoverflow
Solution 5 - C#Chris KlepeisView Answer on Stackoverflow
Solution 6 - C#Jeff OgataView Answer on Stackoverflow
Solution 7 - C#C. Dragon 76View Answer on Stackoverflow
Solution 8 - C#ulty4lifeView Answer on Stackoverflow