C# 问题:我需要使用 LastIndexOf() 向后搜索字符串 有问题的字符串是“South Dakota 1040” 需要从 1040 系统指标中拆分州名。我可以自己获取字符串的“1040”部分,但不能自己获取州名。由于字符串中有两个空格,因此必须向后退。有没有比我正在看的更好的方法来做到这一点?
问问题
9816 次
5 回答
6
用于LastIndexOf
获取最后一个空格。然后将字符串拆分为两部分,您可以使用该SubString
方法执行此操作。
str.SubString(0, str.LastIndexOf(' ')); //this gets you "South Dakota"
LastIndexOf
返回-1时一定要处理。
于 2013-05-16T20:35:18.140 回答
1
在软件开发中有很多方法可以给猫剥皮(注意我对猫或任何其他类型的动物没有不良感觉):) 这些方法都可以,如果你有一个可以确定的特定模式,我更喜欢正则表达式选项到,但这只是我:)
// our string
string x = "South Dakota 1040";
x.Substring(0, x.LastIndexOf(' '));
// this basically does the same as above, but removes anything with a space and numbers
Regex.Replace(x, @"\s\d+", string.Empty);
// this is simmilar to regex above, though you have to watch out for no match cases
Regex.Match(x, @".*?(?=\s\d+)").Value;
于 2013-05-16T20:43:10.230 回答
0
var test = "South Dakota 1040";
var state = test.Remove(test.LastIndexOf(" "));
于 2013-05-16T20:35:53.520 回答
-1
string replaceContent = "1040";
string content = "South Dakota 1040";
string result = content.Replace(replaceContent, "").Trim();
于 2013-05-16T20:41:41.100 回答
-1
此处无需代码狂,逻辑是在 foreach 中截断您的字符串,并连接在单元格/列表中找到的大于位置 [0]/[1] 的字符串。这对你来说足够了吗?
于 2013-05-16T20:33:51.290 回答