删除字符"."之前的字符.

lov*_*iji 45 c#

如何有效地删除字符"."之前放置的字符串中的所有字符?

输入: Amerika.USA

输出: 美国

cas*_*One 117

你可以像这样使用IndexOf方法Substring方法:

string output = input.Substring(input.IndexOf('.') + 1);
Run Code Online (Sandbox Code Playgroud)

以上没有错误处理,因此如果输入字符串中不存在句点,则会出现问题.

  • @casperOne实际上没有IndexOf如果没有找到则返回-1,并且字符串被zerobased用于子串的引用,所以从技术上讲,如果没有句点它将返回整个字符串,对吧?我认为只要字符串不为空就足够了. (7认同)
  • @casperOne ~ 啧啧,它的 -1 `+ 1` ......所以它总是零或更多。你的代码不是我的 ;) (2认同)

小智 24

你可以试试这个:

string input = "lala.bla";
output = input.Split('.').Last();
Run Code Online (Sandbox Code Playgroud)

  • 如果有超过一个1期,你会遇到问题. (4认同)

Ita*_*aro 11

string input = "America.USA"
string output = input.Substring(input.IndexOf('.') + 1);
Run Code Online (Sandbox Code Playgroud)


Ben*_*Ben 6

我常用的扩展方法来解决这个问题:

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;
    }
Run Code Online (Sandbox Code Playgroud)


luk*_*uke 5

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

这将返回新单词。