开发者

Remove characters before character "."

开发者 https://www.devze.com 2023-01-01 18:39 出处:网络
How effectively remove all character in string that placed 开发者_如何学编程before character \".\"?

How effectively remove all character in string that placed 开发者_如何学编程before character "."?

Input: Amerika.USA

Output: USA


You can use the IndexOf method and the Substring method like so:

string output = input.Substring(input.IndexOf('.') + 1);

The above doesn't have error handling, so if a period doesn't exist in the input string, it will present problems.


You could try this:

string input = "lala.bla";
output = input.Split('.').Last();


string input = "America.USA"
string output = input.Substring(input.IndexOf('.') + 1);


String input = ....;
int index = input.IndexOf('.');
if(index >= 0)
{
    return input.Substring(index + 1);
}

This will return the new word.


Extension methods I commonly use to solve this problem:

public static string RemoveAfter(this string value, string character)
    {
        int index = value.IndexOf(character);
        if (index > 0)
        {
            value = value.Substring(0, index);
        }
        return value;
    }

    public static string RemoveBefore(this string value, string character)
    {
        int index = value.IndexOf(character);
        if (index > 0)
        {
            value = value.Substring(index + 1);
        }
        return value;
    }


public string RemoveCharactersBeforeDot(string s)
{
 string splitted=s.Split('.');
 return splitted[splitted.Length-1]
}


A couple of methods that, if the char does not exists, return the original string.

This one cuts the string after the first occurrence of the pivot:

public static string truncateStringAfterChar(string input, char pivot){         
    int index = input.IndexOf(pivot);   
    if(index >= 0) {
        return input.Substring(index + 1);          
    }           
    return input;       
}

This one instead cuts the string after the last occurrence of the pivot:

public static string truncateStringAfterLastChar(string input, char pivot){         
    return input.Split(pivot).Last();   
}
0

精彩评论

暂无评论...
验证码 换一张
取 消