2013-05-03 2 views
-1

나는C#에서 문자의 위치를 ​​찾는 방법은 무엇입니까?

string input = "XXXX-NNNN-A/N"; 
string[] separators = { "-", "/" }; 

내가 문자열에서 seperators의 발생 위치를 찾을 필요가있다.

출력은

5 "-" 
10 "-" 
12 "/" 

어떻게 C#으로 할 것인가?

+1

당신이 문서를 시도

string input = "XXXX-NNNN-A/N"; string[] separators = {"-", "/"}; 

사용하여 검색을 수행이 주어? http://msdn.microsoft.com/en-us/library/11w09h50.aspx – Matthew

+0

그냥이 게시물을 따릅니다. http://stackoverflow.com/questions/541954/how-would-you-count-occurences -of-a-string-within-a-string-c? rq = 1 –

+3

string.IndexOf (...), string.IndexOfAny (...), string.LastIndexOf (...), string을 확인하십시오. LastIndexOfAny (...) 메소드. – Artemix

답변

1

이 시도 :

string input = "XXXX-NNNN-A/N"; 
char[] seperators = new[] { '/', '-' }; 
Dictionary<int, char> positions = new Dictionary<int,char>(); 
for (int i = 0; i < input.Length; i++) 
    if (seperators.Contains(input[i])) 
     positions.Add(i + 1, input[i]); 

foreach(KeyValuePair<int, char> pair in positions) 
    Console.WriteLine(pair.Key + " \"" + pair.Value + "\""); 
1

String.IndexOf() 메소드에서 0부터 시작하는 위치 인덱스를 얻을 수 있습니다.

1
List<int> FindThem(string theInput) 
{ 
    List<int> theList = new List<int>(); 
    int i = 0; 
    while (i < theInput.Length) 
     if (theInput.IndexOfAny(new[] { '-', '/' }, i) >= 0) 
     { 
      theList.Add(theInput.IndexOfAny(new[] { '-', '/' }, i) + 1); 
      i = theList.Last(); 
     } 
     else break; 
    return theList; 
} 
+0

문자열이 구분 기호로 시작하면'> = 0'이되어야합니다. – Matthew

+0

@Matthew 당신은 중간 편집에서 나를 붙 잡았습니다. 당신은 물론 정확합니다. – ispiro

+0

이유 : i = theList.Last() + 1; 나는 내가 ++로 충분하다고 생각한다. –

2
for (int i = 0; i < input.Length; i++) 
{ 
    for (int j = 0; j < separators.Length; j++) 
    { 
     if (input[i] == separators[j]) 
      Console.WriteLine((i + 1) + "\"" + separators[j] + "\""); 
    } 
} 
0

이 시도 :

int index = 0;             // Starting at first character 
char[] separators = "-/".ToCharArray(); 
while (index < input.Length) { 
    index = input.IndexOfAny(separators, index);    // Find next separator 
    if (index < 0) break; 
    Debug.WriteLine((index+1).ToString() + ": " + input[index]); 
    index++; 
} 
+0

분리자를 문자 배열로 변환하는 이유는 무엇입니까? –

+0

왜'index.ToString()'인가? –

+0

@MartinMulder :' "- /"ToCharArray()'는 반드시 루프 외부에서 수행되어야합니다. – joe

1

꼭 같은 물건 LINQ를 사랑 해요.

var found = input.Select((c, i) => new {c = c, i = i}) 
      .Where(x => separators.ToList().Contains(x.c.ToString())); 

출력을이 같은 예를 들면 다음과 같습니다 :

found.ToList().ForEach(element => 
         Console.WriteLine(element.i + " \"" + element.c + "\"")); 
+0

또는 x => (new [] { "-", "new", "new", "new" ToList() .ForEach (element => Console.WriteLine (element.i + "\" "element.c +"\ "")));) : – ispiro

+0

물론 가능합니다.나는 약간의 교육학적인 시도를하려고 노력했다. ;) – Kjartan

관련 문제