LastIndexOf() method

本文关键字:method LastIndexOf | 更新日期: 2023-09-27 18:13:53

c#问题:我需要使用LastIndexOf()在字符串上向后搜索问题的字符串是"南达科他州1040"需要将1040系统指示灯的状态名称拆分。我可以单独获得字符串的"1040"部分,但不能单独获得州名。必须倒回去,因为字符串中有两个空格。有没有比我现在看到的更好的办法?

LastIndexOf() method

使用LastIndexOf获取最后一个空格。然后将字符串分成两部分,您可以使用SubString方法执行此操作。

str.SubString(0, str.LastIndexOf(' ')); //this gets you "South Dakota"

确保LastIndexOf返回-1时处理

在软件开发中有很多方法可以给猫剥皮(注意,我对猫或任何其他类型的动物没有恶感):)这些方法都可以工作,如果你有一个特定的模式,我更喜欢regex选项,但这只是我的看法:)

// 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;
var test = "South Dakota 1040";
var state = test.Remove(test.LastIndexOf(" "));

这里没有代码怪胎,逻辑是在foreach中截断字符串并连接在位置大于[0]/[1]的单元格/列表中找到的字符串。这对您够了吗?

 string replaceContent = "1040";
 string content = "South Dakota 1040";
 string result = content.Replace(replaceContent, "").Trim();