我有3种可能的输入案例
string input = ""; // expected result: ""
string input = "bar-foo"; // expected result: "foo"
string input = "foo"; // expected result: "foo"
而且我必须删除包括第一个分隔符char
-
(如果存在)的所有内容。工作方法:
string output = input.Split('-').LastOrDefault();
我想在没有
Split()
的情况下解决此问题-我的无效方法:string output = input.Substring(input.IndexOf('-') );
如何处理
IndexOutOfRangeException
/使此代码起作用? 最佳答案
尝试添加1
:
string output = input.Substring(input.LastIndexOf('-') + 1);
如果
-
中没有input
,则LastIndexOf
返回-1
,因此您将拥有整个字符串。我假设您正在寻找
input
的后缀,这就是为什么我放入LastIndexOf
的原因:"123-456-789" -> "789"
如果要剪掉前缀:
"123-456-789" -> "456-789"
请将
LastIndexOf
更改为IndexOf
关于c# - 删除子字符串(如果存在),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50906297/