在两个点之间获取字符串c#

时间:2014-04-07 11:29:22

标签: c#

我怎样才能在两个点之间获得字符串?

  

[Person.Position.Name]

对于这种情况,我想得到字符串" Position"

我也可以有三个点......

  

[Person.Location.City.Name]

我想在点之间取所有字符串

3 个答案:

答案 0 :(得分:3)

我知道这是一年前的问题,但其他答案还不够,就像他们甚至假装你想要“Location.City”一样,因为他们不知道如何分开它们。解决方案虽然简单,但是不要使用indexof。 说你要分开四个(不是3个)部分:

String input = "Person.Location.City.Name"
        string person = input.Split('.')[0];
        string location = input.Split('.')[1];
        string city = input.Split('.')[2];
        string name = input.Split('.')[3];

Console.WriteLine("Person: " + person + "\nLocation: " + location + "\nCity: " + city + "\nName: " + name);

答案 1 :(得分:2)

这可能会对您有所帮助:

string s = "Person.Position.Name";
int start = s.IndexOf(".") + 1;
int end = s.LastIndexOf(".");
string result = s.Substring(start, end - start);

它将返回第一个和最后一个点之间的所有值。

如果您不希望字符串之间带有点的结果,可以尝试:

string s = "Person.Location.Name";
int start = s.IndexOf(".") + 1;
int end = s.LastIndexOf(".");
var result = s.Substring(start, end - start).Split('.');

foreach (var item in result)
{
    //item is  some string between the first and the last dot.
    //in this case "Location"
}

答案 2 :(得分:0)

试试这个

string str = "[Person.Location.City.Name]";
int dotFirstIndex = str.IndexOf('.');
int dotLastIndex = str.LastIndexOf('.');
string result = str.Substring((dotFirstIndex + 1), (dotLastIndex - dotFirstIndex) - 1); // output Location.City
相关问题