how to remove all text after the last recurrence o

2019-04-21 09:04发布

given any string, i want to remove any letters after a specific character.

this character may exist multiple times in the string and i only want to apply this to the last occurrance.

so lets say "/" is the character, here are some examples:

http://www.ibm.com/test ==> http://www.ibm.com
hello/test ==> hello

2条回答
叼着烟拽天下
2楼-- · 2019-04-21 09:39

Another options is to use String.Remove

 modifiedText = text.Remove(text.LastIndexOf(separator));

With some error checking the code can be extracted to an extension method like:

public static class StringExtensions
{
    public static string RemoveTextAfterLastChar(this string text, char c)
    {
        int lastIndexOfSeparator;

        if (!String.IsNullOrEmpty(text) && 
            ((lastIndexOfSeparator = text.LastIndexOf(c))  > -1))
        {

            return text.Remove(lastIndexOfSeparator);
        }
        else
        {
            return text;
        }
    }
 }

It could be used like:

private static void Main(string[] args)
{
    List<string> inputValues = new List<string>
    {
        @"http://www.ibm.com/test",
        "hello/test",
        "//",
        "SomethingElseWithoutDelimiter",
        null,
        "     ", //spaces
    };

    foreach (var str in inputValues)
    {
        Console.WriteLine("\"{0}\" ==> \"{1}\"", str, str.RemoveTextAfterLastChar('/'));
    }
}

Output:

"http://www.ibm.com/test" ==> "http://www.ibm.com"
"hello/test" ==> "hello"
"//" ==> "/"
"SomethingElseWithoutDelimiter" ==> "SomethingElseWithoutDelimiter"
"" ==> ""
"     " ==> "     "
查看更多
▲ chillily
3楼-- · 2019-04-21 09:52
if (text.Contains('/'))
    text = text.Substring(0, text.LastIndexOf('/'));

or

var pos = text.LastIndexOf('/');
if (pos >= 0)
    text = text.Substring(0, pos);

(edited to cover the case when '/' does not exist in the string, as mentioned in comments)

查看更多
登录 后发表回答