나는C#에서 문자의 위치를 찾는 방법은 무엇입니까?
string input = "XXXX-NNNN-A/N";
string[] separators = { "-", "/" };
내가 문자열에서 seperators의 발생 위치를 찾을 필요가있다.
출력은
5 "-"
10 "-"
12 "/"
어떻게 C#으로 할 것인가?
나는C#에서 문자의 위치를 찾는 방법은 무엇입니까?
string input = "XXXX-NNNN-A/N";
string[] separators = { "-", "/" };
내가 문자열에서 seperators의 발생 위치를 찾을 필요가있다.
출력은
5 "-"
10 "-"
12 "/"
어떻게 C#으로 할 것인가?
이 시도 :
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 + "\"");
String.IndexOf()
메소드에서 0부터 시작하는 위치 인덱스를 얻을 수 있습니다.
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;
}
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] + "\"");
}
}
이 시도 :
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++;
}
분리자를 문자 배열로 변환하는 이유는 무엇입니까? –
왜'index.ToString()'인가? –
@MartinMulder :' "- /"ToCharArray()'는 반드시 루프 외부에서 수행되어야합니다. – joe
꼭 같은 물건 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 + "\""));
당신이 문서를 시도
사용하여 검색을 수행이 주어? http://msdn.microsoft.com/en-us/library/11w09h50.aspx – Matthew
그냥이 게시물을 따릅니다. http://stackoverflow.com/questions/541954/how-would-you-count-occurences -of-a-string-within-a-string-c? rq = 1 –
string.IndexOf (...), string.IndexOfAny (...), string.LastIndexOf (...), string을 확인하십시오. LastIndexOfAny (...) 메소드. – Artemix