如何有效地删除字符串中放在“ .”前面的所有字符?
输入: 美国,美国
产出: 美国
你可以这样使用 IndexOf法和 Substring方法:
IndexOf
Substring
string output = input.Substring(input.IndexOf('.') + 1);
上面没有错误处理,所以如果输入字符串中不存在句点,就会出现问题。
String input = ....; int index = input.IndexOf('.'); if(index >= 0) { return input.Substring(index + 1); }
这将返回新单词。
string input = "America.USA" string output = input.Substring(input.IndexOf('.') + 1);
public string RemoveCharactersBeforeDot(string s) { string splitted=s.Split('.'); return splitted[splitted.Length-1] }
你可以试试这个:
string input = "lala.bla"; output = input.Split('.').Last();
两个方法,如果字符不存在,则返回原始字符串。
这个在第一次出现 pivot 之后切断字符串:
public static string truncateStringAfterChar(string input, char pivot){ int index = input.IndexOf(pivot); if(index >= 0) { return input.Substring(index + 1); } return input; }
这个函数在 pivot 的最后一次出现之后切断字符串:
public static string truncateStringAfterLastChar(string input, char pivot){ return input.Split(pivot).Last(); }
我通常用来解决这个问题的扩展方法:
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; }