Znajdź n-te wystąpienie znaku w ciągu


83

Potrzebuję pomocy przy tworzeniu metody C #, która zwraca indeks n-tego wystąpienia znaku w ciągu.

Na przykład trzecie wystąpienie znaku 't'w ciągu "dtststxtu"to 5.
(Zwróć uwagę, że ciąg ma 4 tsekundy).


Z czym masz do tej pory pracować?
Anthony Forloney

3
Zredagowałem Twoją odpowiedź, aby jaśniej wyrazić, czego chcesz. Miejmy nadzieję, że otrzymasz odpowiedzi pasujące do pytania. Brak biegłości w języku angielskim nie jest problemem w Stack Overflow, zawsze możesz po prostu dodać wiersz z prośbą o zmianę pytania i wyczyszczenie go przez kogoś bardziej biegłego, ale musisz sam postarać się podać kilka przykładów w pytaniu, aby ludzie zrozumieli, co potrzebujesz.
Lasse V. Karlsen

Odpowiedzi:


94
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;
}

Można to uczynić znacznie czystszym i nie ma żadnych kontroli na wejściu.


7
Świetne podejście. Ładny i czysty, łatwy do odczytania, łatwy w utrzymaniu i doskonała wydajność.
Mike

1
miłość do pętli takich jak te, nie tylko zapewniają doskonałą wydajność, ale nie możesz się z nimi pomylić, ponieważ wszystko jest krystalicznie czyste i tuż przed twoimi oczami. Piszesz linq, a 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

20

W poprzednim rozwiązaniu występuje drobny błąd.

Oto zaktualizowany kod:

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

1
Co zwróci, jeśli postać nie zostanie znaleziona?
Timuçin,

Zwraca długość / liczbę ciągów s. Musisz sprawdzić tę wartość.
Yoky

10

Oto inne rozwiązanie 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);
}

Dla zabawy, oto rozwiązanie Regex. Widziałem, że niektórzy początkowo używali Regex do liczenia, ale kiedy pytanie się zmieniło, nie wprowadzono żadnych aktualizacji. Oto, jak można to zrobić z Regex - znowu dla zabawy. Tradycyjne podejście jest najlepsze dla prostoty.

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!");

9

Oto rekurencyjna implementacja - jako metoda rozszerzająca, naśladująca format metody (metod) frameworka:

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 kilka testów jednostkowych (MBUnit), które mogą Ci pomóc (udowodnić, że są 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));
}

8

Aktualizacja: Jednowierszowy indeks N-tego wystąpienia:

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

Używaj ich na własne ryzyko. To wygląda na pracę domową, więc zostawiłem tam kilka błędów do znalezienia:

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;
}

4
Twój jednoliniowy przykład nie działa, ponieważ wartość n nigdy się nie zmienia.
Dave Neeley

2
Fajne rozwiązanie, chociaż nie jest to prawdziwa „jednolinijka”, ponieważ zmienna musi być zdefiniowana poza zakresem lambda. s.TakeWhile (c => ((n - = (c == 't'))? 1: 0)> 0) .Count ();
nieważne

12
−1, „więc zostawiłem tam kilka błędów do znalezienia”
Zanon,

6

ranomore słusznie skomentował, że jedna linijka Joela Coehoorna nie działa.

Oto dwuwierszowy, który działa, metoda rozszerzenia ciągu, która zwraca indeks oparty na 0 n-tym wystąpieniu znaku lub -1, jeśli nie istnieje n-te wystąpienie:

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;
    }
}

4

Odpowiedź Joela jest dobra (i zagłosowałem za nią). Oto rozwiązanie oparte na LINQ:

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

2
@Andrew - możesz to skrócić, pomijając Wherei przekazując predykat do Countmetody. Nie żeby było coś złego w tym, jak to jest.
Mike Two

10
Czy to nie wystarczy, aby znaleźć liczbę wystąpień znaku zamiast indeksu n-tego?
dx_over_dt

4

Dodaję kolejną odpowiedź, która działa dość szybko w porównaniu z innymi metodami

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;
}

3

Oto świetny sposób na zrobienie tego

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

3
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 'bansal.vks@gmail.com'"; // 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

2

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

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

pozdrowienia.


2

Ponieważ funkcja wbudowana IndexOfjest już zoptymalizowana pod kątem wyszukiwania znaku w ciągu, jeszcze szybszą wersją byłaby (jako metoda 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;
}

Lub wyszukaj od końca ciągu za pomocą 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;
}

Wyszukiwanie ciągu zamiast znaku jest tak proste, jak zmiana typu parametru z charna stringi opcjonalnie dodanie przeciążenia, aby określić StringComparison.


2

jeśli jesteś zainteresowany, możesz również utworzyć metody rozszerzające ciąg, takie jak:

     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;
    }

2

Oto kolejna, być może prostsza implementacja stringów IndexOfNth()z implementacją stringów.

Oto stringwersja dopasowania:

public static int IndexOfNth(this string source, string matchString, 
                             int charInstance, 
                             StringComparison stringComparison = StringComparison.CurrentCulture)
{
    if (string.IsNullOrEmpty(source))
        return -1;

    int lastPos = 0;
    int count = 0;

    while (count < charInstance )
    {
        var len = source.Length - lastPos;
        lastPos = source.IndexOf(matchString, lastPos,len,stringComparison);
        if (lastPos == -1)
            break;

        count++;
        if (count == charInstance)
            return lastPos;

        lastPos += matchString.Length;
    }
    return -1;
}

i charwersja meczu:

public static int IndexOfNth(string source, char matchChar, int charInstance)        
{
    if (string.IsNullOrEmpty(source))
        return -1;

    if (charInstance < 1)
        return -1;

    int count = 0;
    for (int i = 0; i < source.Length; i++)
    {
        if (source[i] == matchChar)
        {
            count++;
            if (count == charInstance)                 
                return i;                 
        }
    }
    return -1;
}

Myślę, że w przypadku tak niskiego poziomu implementacji chciałbyś trzymać się z daleka od używania LINQ, RegEx lub rekurencji, aby zmniejszyć narzut.


1

Inne rozwiązanie oparte na RegEx (nieprzetestowane):

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;
}

Powinno to być nieco bardziej optymalne niż wymaganie wyrażenia regularnego do utworzenia kolekcji Dopasowania, tylko po to, aby odrzucić wszystkie dopasowania oprócz jednego.


W odpowiedzi na komentarz do kolekcji Matches (ponieważ to właśnie pokazałem w mojej odpowiedzi): Przypuszczam, że bardziej wydajnym podejściem byłoby użycie pętli while do sprawdzania match.Successi pobierania NextMatchpodczas zwiększania licznika i przerywania wcześniej, gdy counter == index.
Ahmad Mageed

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 ;
    }

1

Cześć wszystkim, stworzyłem dwie metody przeciążania do znajdowania n-tego wystąpienia znaku i tekstu o mniejszej złożoności bez przechodzenia przez pętlę, co zwiększa wydajność aplikacji.

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

Rozszerzony LINQ Marca Calsa dla ogólnych.

   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;
           }
       }
   }

Kilka testów.

   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();
           }


}

}


1
public static int IndexOfAny(this string str, string[] values, int startIndex, out string selectedItem)
    {
        int first = -1;
        selectedItem = null;
        foreach (string item in values)
        {
            int i = str.IndexOf(item, startIndex, StringComparison.OrdinalIgnoreCase);
            if (i >= 0)
            {
                if (first > 0)
                {
                    if (i < first)
                    {
                        first = i;
                        selectedItem = item;
                    }
                }
                else
                {
                    first = i;
                    selectedItem = item;
                }
            }
        }
        return first;
    }

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.