2010-04-03 24 views
62

Potrzebuję pomocy w tworzeniu metody C#, która zwraca indeks N-tego wystąpienia znaku w ciągu znaków.Znajdź N-te wystąpienie znaku w ciągu znaków

Na przykład, 3. występowanie charakteru 't' w ciągu "dtststxtu" to 5.
(Zauważ, że ciąg ma 4 t s.)

+0

Co trzeba pracować z tak daleko? –

+1

Edytowałem twoją odpowiedź, aby wyraźniej przekazać to, czego chcesz. Mamy nadzieję, że otrzymasz odpowiedzi, które pasują do pytania. Brak płynności w języku angielskim nie jest problemem w Stack Overflow, zawsze możesz po prostu dodać wiersz z prośbą kogoś, kto bardziej płynnie edytuje twoje pytanie i posprząta, ale musisz sam starać się podać kilka przykładów w pytaniu, aby ludzie zrozumieli co potrzebujesz. –

Odpowiedz

60
public int GetNthIndex(string s, char t, int n) 
{ 
    int count = 0; 
    for (int i = 0; i < s.Length; i++) 
    { 
     if (s[i] == t) 
     { 
      count++; 
      if (count == n) 
      { 
       return i; 
      } 
     } 
    } 
    return -1; 
} 

To może być wykonane wiele czystsze, i nie ma kontroli na wejściu.

+5

Świetne podejście. Ładne i czyste, łatwe do odczytania, łatwe w utrzymaniu i doskonałej wydajności. – Mike

+0

Uwielbiam takie pętle, nie tylko dają doskonałe wyniki, ale nie możesz się z nimi nieźle, ponieważ wszystko jest krystalicznie czyste i tuż przed twoimi oczami. Piszesz linq i jakiś programista umieszcza go w pętli, nie rozumiejąc kosztów i wszyscy zastanawiają się, gdzie jest wąskie gardło wydajności. – user734028

11

Aktualizacja: Indeks n-tego wystąpienia jednej liniowej:

int NthOccurence(string s, char t, int n) 
{ 
    s.TakeWhile(c => n - (c == t)?1:0 > 0).Count(); 
} 

Użyj ich na własne ryzyko. To wygląda na pracę domową, więc zostawiłem kilka błędów, aby znaleźć:

int CountChars(string s, char t) 
{ 
    int count = 0; 
    foreach (char c in s) 
     if (s.Equals(t)) count ++; 
    return count; 
} 

.

int CountChars(string s, char t) 
{ 
    return s.Length - s.Replace(t.ToString(), "").Length; 
} 

.

int CountChars(string s, char t) 
{ 
    Regex r = new Regex("[\\" + t + "]"); 
    return r.Match(s).Count; 
} 
+2

Twój przykład jednej linijki nie działa, ponieważ wartość n nigdy nie jest zmieniana. –

+2

Ładne rozwiązanie, choć nie jest to prawdziwa "jedna liniówka", ponieważ zmienna musi być zdefiniowana poza zasięgiem lambda. s.TakeWhile (c => ((n - = (c == 't'))?1: 0)> 0) .Count(); – nullable

+0

-1, "więc zostawiłem tam kilka błędów, aby znaleźć" – Zanon

4

Odpowiedź Joela jest dobra (i przegłosowałem ją). Oto rozwiązanie oparte na LINQ-a:

yourString.Where(c => c == 't').Count(); 
+2

@Andrew - możesz to skrócić, pomijając 'Where' i przekazując predykat do metody' Count'. Nie chodzi o to, że coś jest nie tak z tym, czym jest. –

+9

Czy nie będzie to tylko liczba wystąpień postaci, a nie indeks n-tego? – dfoverdx

7

Oto kolejny roztwór LINQ:

string input = "dtststx"; 
char searchChar = 't'; 
int occurrencePosition = 3; // third occurrence of the char 
var result = input.Select((c, i) => new { Char = c, Index = i }) 
        .Where(item => item.Char == searchChar) 
        .Skip(occurrencePosition - 1) 
        .FirstOrDefault(); 

if (result != null) 
{ 
    Console.WriteLine("Position {0} of '{1}' occurs at index: {2}", 
         occurrencePosition, searchChar, result.Index); 
} 
else 
{ 
    Console.WriteLine("Position {0} of '{1}' not found!", 
         occurrencePosition, searchChar); 
} 

Tak dla zabawy, oto rozwiązanie Regex. Widziałem, jak niektórzy ludzie początkowo stosowali Regex do policzenia, ale kiedy pytanie się zmieniło, nie wprowadzono żadnych aktualizacji. Oto jak można to zrobić z Regeksem - znowu, tylko dla zabawy. Tradycyjne podejście jest najlepsze ze względu na prostotę.

string input = "dtststx"; 
char searchChar = 't'; 
int occurrencePosition = 3; // third occurrence of the char 

Match match = Regex.Matches(input, Regex.Escape(searchChar.ToString())) 
        .Cast<Match>() 
        .Skip(occurrencePosition - 1) 
        .FirstOrDefault(); 

if (match != null) 
    Console.WriteLine("Index: " + match.Index); 
else 
    Console.WriteLine("Match not found!"); 
3

Oto świetny sposób, aby zrobić to

 int i = 0; 
    string s="asdasdasd"; 
    int n = 3; 
    s.Where(b => (b == 'd') && (i++ == n)); 
    return i; 
1

Innym rozwiązaniem regex opartych (niesprawdzone):

int NthIndexOf(string s, char t, int n) { 
    if(n < 0) { throw new ArgumentException(); } 
    if(n==1) { return s.IndexOf(t); } 
    if(t=="") { return 0; } 
    string et = RegEx.Escape(t); 
    string pat = "(?<=" 
     + Microsoft.VisualBasic.StrDup(n-1, et + @"[.\n]*") + ")" 
     + et; 
    Match m = RegEx.Match(s, pat); 
    return m.Success ? m.Index : -1; 
} 

ten powinien być nieco bardziej optymalne niż wymagające regex do stworzenia Dopasowuje kolekcję, tylko po to, by odrzucić wszystkie oprócz jednego meczu.

+0

W odpowiedzi na komentarz do kolekcji Mecze (ponieważ to było to, co pokazałem w mojej odpowiedzi): Przypuszczam, że bardziej efektywnym podejściem byłoby użycie pętli while sprawdzającej 'match.Success' i pobranie' NextMatch' podczas zwiększania wartości licznik i łamanie wcześnie, gdy "counter == index". –

1
public static int FindOccuranceOf(this string str,char @char, int occurance) 
    { 
     var result = str.Select((x, y) => new { Letter = x, Index = y }) 
      .Where(letter => letter.Letter == @char).ToList(); 
     if (occurence > result.Count || occurance <= 0) 
     { 
      throw new IndexOutOfRangeException("occurance"); 
     } 
     return result[occurance-1].Index ; 
    } 
8

Oto rekurencyjna realizacja - jako metodę rozszerzenia, dokładnie taki efekt formatu metody ramowej (ów):

public static int IndexOfNth(
    this string input, string value, int startIndex, int nth) 
{ 
    if (nth < 1) 
     throw new NotSupportedException("Param 'nth' must be greater than 0!"); 
    if (nth == 1) 
     return input.IndexOf(value, startIndex); 

    return input.IndexOfNth(value, input.IndexOf(value, startIndex) + 1, --nth); 
} 

oto niektóre (MbUnit) testy jednostkowe, które mogą Ci pomóc (aby udowodnić, że jest poprawne):

[Test] 
public void TestIndexOfNthWorksForNth1() 
{ 
    const string input = "foo<br />bar<br />baz<br />"; 
    Assert.AreEqual(3, input.IndexOfNth("<br />", 0, 1)); 
} 

[Test] 
public void TestIndexOfNthWorksForNth2() 
{ 
    const string input = "foo<br />whatthedeuce<br />kthxbai<br />"; 
    Assert.AreEqual(21, input.IndexOfNth("<br />", 0, 2)); 
} 

[Test] 
public void TestIndexOfNthWorksForNth3() 
{ 
    const string input = "foo<br />whatthedeuce<br />kthxbai<br />"; 
    Assert.AreEqual(34, input.IndexOfNth("<br />", 0, 3)); 
} 
4

ranomore słusznie zauważył, że Joel Coehoorn za jedno-liner nie działa.

Oto dwa-liner że robi pracy, metodę rozszerzenia ciąg, który zwraca indeks 0 opartego na n-tego wystąpienia znaku, lub -1 jeśli nie nth występowanie istnieje:

public static class StringExtensions 
{ 
    public static int NthIndexOf(this string s, char c, int n) 
    { 
     var takeCount = s.TakeWhile(x => (n -= (x == c ? 1 : 0)) > 0).Count(); 
     return takeCount == s.Length ? -1 : takeCount; 
    } 
} 
1

możesz wykonywać tę pracę za pomocą wyrażeń regularnych.

 string input = "dtststx"; 
     char searching_char = 't'; 
     int output = Regex.Matches(input, "["+ searching_char +"]")[2].Index; 

najlepszy szacunek.

16

Występuje drobny błąd w poprzednim rozwiązaniu.

Oto zaktualizowany kod:

s.TakeWhile(c => (n -= (c == t ? 1 : 0)) > 0).Count(); 
+1

Co zwróci, jeśli znak nie zostanie znaleziony? –

+0

Zwraca długość/liczyć ciąg s. Musisz sprawdzić tę wartość. – Yoky

1

Witam wszystkich Stworzyłem dwie metody przeciążeniem znalezienia n-tego wystąpienia char i tekstu z mniejszą złożoność bez poruszania się pętli, co zwiększa wydajność Twoje zgłoszenie.

public static int NthIndexOf(string text, char searchChar, int nthindex) 
{ 
    int index = -1; 
    try 
    { 
     var takeCount = text.TakeWhile(x => (nthindex -= (x == searchChar ? 1 : 0)) > 0).Count(); 
     if (takeCount < text.Length) index = takeCount; 
    } 
    catch { } 
    return index; 
} 
public static int NthIndexOf(string text, string searchText, int nthindex) 
{ 
    int index = -1; 
    try 
    { 
     Match m = Regex.Match(text, "((" + searchText + ").*?){" + nthindex + "}"); 
     if (m.Success) index = m.Groups[2].Captures[nthindex - 1].Index; 
    } 
    catch { } 
    return index; 
} 
1

Ponieważ wbudowaną IndexOf funkcji jest już zoptymalizowany do przeszukiwania postać ciągu znaków, jeszcze szybsza wersja będzie (jako metodę rozszerzenia):

public static int NthIndexOf(this string input, char value, int n) 
{ 
    if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero."); 

    int i = -1; 
    do 
    { 
     i = input.IndexOf(value, i + 1); 
     n--; 
    } 
    while (i != -1 && n > 0); 

    return i; 
} 

Albo szukaj od końca łańcucha przy użyciu LastIndexOf:

public static int NthLastIndexOf(this string input, char value, int n) 
{ 
    if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero."); 

    int i = input.Length; 
    do 
    { 
     i = input.LastIndexOf(value, i - 1); 
     n--; 
    } 
    while (i != -1 && n > 0); 

    return i; 
} 

Poszukiwanie ciągu znaków, a nie charakteru jest tak proste, jak zmiana typu parametru od char do string i opcjonalnie dodaj przeciążenie, aby określić StringComparison.

2
public int GetNthOccurrenceOfChar(string s, char c, int occ) 
{ 
    return String.Join(c.ToString(), s.Split(new char[] { c }, StringSplitOptions.None).Take(occ)).Length; 
} 
3
string result = "i am '[email protected]'"; // string 

int in1 = result.IndexOf('\''); // get the index of first quote 

int in2 = result.IndexOf('\'', in1 + 1); // get the index of second 

string quoted_text = result.Substring(in1 + 1, in2 - in1); // get the string between quotes 
3

dodam kolejną odpowiedź, że biegną dość szybko w porównaniu do innych metod

private static int IndexOfNth(string str, char c, int nth, int startPosition = 0) 
{ 
    int index = str.IndexOf(c, startPosition); 
    if (index >= 0 && nth > 1) 
    { 
     return IndexOfNth(str, c, nth - 1, index + 1); 
    } 

    return index; 
} 
1

Marc licencji CAL LINQ przedłużony o rodzajowy.

using System; 
    using System.Collections.Generic; 
    using System.Linq; 

    namespace fNns 
    { 
     public class indexer<T> where T : IEquatable<T> 
     { 
      public T t { get; set; } 
      public int index { get; set; } 
     } 
     public static class fN 
     { 
      public static indexer<T> findNth<T>(IEnumerable<T> tc, T t, 
       int occurrencePosition) where T : IEquatable<T> 
      { 
       var result = tc.Select((ti, i) => new indexer<T> { t = ti, index = i }) 
         .Where(item => item.t.Equals(t)) 
         .Skip(occurrencePosition - 1) 
         .FirstOrDefault(); 
       return result; 
      } 
      public static indexer<T> findNthReverse<T>(IEnumerable<T> tc, T t, 
     int occurrencePosition) where T : IEquatable<T> 
      { 
       var result = tc.Reverse<T>().Select((ti, i) => new indexer<T> {t = ti, index = i }) 
         .Where(item => item.t.Equals(t)) 
         .Skip(occurrencePosition - 1) 
         .FirstOrDefault(); 
       return result; 
      } 
     } 
    } 

Niektóre testy.

using System; 
    using System.Collections.Generic; 
    using NUnit.Framework; 
    using Newtonsoft.Json; 
    namespace FindNthNamespace.Tests 
    { 

     public class fNTests 
     { 
      [TestCase("pass", "dtststx", 't', 3, Result = "{\"t\":\"t\",\"index\":5}")] 
      [TestCase("pass", new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 
     0, 2, Result="{\"t\":0,\"index\":10}")] 
      public string fNMethodTest<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T> 
      { 
       Console.WriteLine(scenario); 
       return JsonConvert.SerializeObject(fNns.fN.findNth<T>(tc, t, occurrencePosition)).ToString(); 
      } 

      [TestCase("pass", "dtststxx", 't', 3, Result = "{\"t\":\"t\",\"index\":6}")] 
      [TestCase("pass", new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 
     0, 2, Result = "{\"t\":0,\"index\":19}")] 
      public string fNMethodTestReverse<T>(string scenario, IEnumerable<T> tc, T t, int occurrencePosition) where T : IEquatable<T> 
      { 
       Console.WriteLine(scenario); 
       return JsonConvert.SerializeObject(fNns.fN.findNthReverse<T>(tc, t, occurrencePosition)).ToString(); 
      } 


} 

}

2

jeśli zainteresowany można również utworzyć metody rozszerzenie ciąg tak:

 public static int Search(this string yourString, string yourMarker, int yourInst = 1, bool caseSensitive = true) 
    { 
     //returns the placement of a string in another string 
     int num = 0; 
     int currentInst = 0; 
     //if optional argument, case sensitive is false convert string and marker to lowercase 
     if (!caseSensitive) { yourString = yourString.ToLower(); yourMarker = yourMarker.ToLower(); } 
     int myReturnValue = -1; //if nothing is found the returned integer is negative 1 
     while ((num + yourMarker.Length) <= yourString.Length) 
     { 
      string testString = yourString.Substring(num, yourMarker.Length); 

      if (testString == yourMarker) 
      { 
       currentInst++; 
       if (currentInst == yourInst) 
       { 
        myReturnValue = num; 
        break; 
       } 
      } 
      num++; 
     }   
     return myReturnValue; 
    } 

    public static int Search(this string yourString, char yourMarker, int yourInst = 1, bool caseSensitive = true) 
    { 
     //returns the placement of a string in another string 
     int num = 0; 
     int currentInst = 0; 
     var charArray = yourString.ToArray<char>(); 
     int myReturnValue = -1; 
     if (!caseSensitive) 
     { 
      yourString = yourString.ToLower(); 
      yourMarker = Char.ToLower(yourMarker); 
     } 
     while (num <= charArray.Length) 
     {     
      if (charArray[num] == yourMarker) 
      { 
       currentInst++; 
       if (currentInst == yourInst) 
       { 
        myReturnValue = num; 
        break; 
       } 
      } 
      num++; 
     } 
     return myReturnValue; 
    } 
Powiązane problemy