2014-04-07 3 views
1

어떻게 두 점 사이에 문자열을 가져올 수 있습니까? 나는 또한 세 개의 점을 가질 수있는 문자열 "위치"두 도트 사이에 문자열 가져 오기 C#

를 얻으려면이 경우에 [Person.Position.Name]

....

[Person.Location.City.Name]

나는 점

+4

찾기 위치 중간 부분을 얻기 위해 마지막 도트를 사용 문자열의 위치를 ​​찾을 수 : 당신이 (안 3) 부분을 분리해서하고 싶은 말은. –

+0

[Person.Location.City.Name]이'Location.City'를 반환해야 함을 의미합니다. –

+2

마지막 예에서'Location.City' 또는'Location'과'City'를 원하십니까? – sloth

답변

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" 
} 
+0

이것이 더 좋을 것입니다.>'int end = s.IndexOf (".", start);' – Yahya

+0

@Yahya 여기에서 시도해 보니 두 번째 값만 반환됩니다. 'LastIndexOf'를 사용하면 처음과 마지막 점 사이의 모든 것을 반환합니다. –

+1

네, 맞습니다. – Yahya

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 
3

을 시도 나는 그것이 세 질문 알지만, 다른 대답은 충분하지 않습니다. 마치 "Location.City"를 구분하는 방법을 모르기 때문에 "Location.City"를 원한다고 생각하는 것처럼 말입니다. 솔루션은 간단하지만 indexof를 사용하지 마십시오. 먼저 점의

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); 
관련 문제