【发布时间】:2010-06-02 15:52:17
【问题描述】:
如何有效地删除字符串中位于字符“.”之前的所有字符?
输入: 美国.美国
输出: 美国
【问题讨论】:
-
是否总是只有一个时期?
标签: c#
如何有效地删除字符串中位于字符“.”之前的所有字符?
输入: 美国.美国
输出: 美国
【问题讨论】:
标签: c#
您可以像这样使用IndexOf method 和Substring method:
string output = input.Substring(input.IndexOf('.') + 1);
上面没有错误处理,所以如果输入字符串中不存在句点,就会出现问题。
【讨论】:
+ 1 ... 所以它总是为零或更多。你的代码不是我的;)
你可以试试这个:
string input = "lala.bla";
output = input.Split('.').Last();
【讨论】:
C 而不是 B.C 给出他的问题和示例。似乎他有一个由点分隔的层次结构。您作为层次结构的A.B.C 示例类似于PlanetEarth.America.USA。他可能仍想捕获层次结构中的最后一项:USA
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);
}
这将返回新单词。
【讨论】:
public string RemoveCharactersBeforeDot(string s)
{
string splitted=s.Split('.');
return splitted[splitted.Length-1]
}
【讨论】:
如果 char 不存在,则返回原始字符串的几个方法。
这个在第一次出现枢轴后切断字符串:
public static string truncateStringAfterChar(string input, char pivot){
int index = input.IndexOf(pivot);
if(index >= 0) {
return input.Substring(index + 1);
}
return input;
}
这个是在最后一次出现枢轴之后切断字符串:
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;
}
【讨论】: