2010-04-03 12 views
62

Ho bisogno di aiuto per la creazione di un metodo C# che restituisca l'indice dell'occorrenza di un carattere in una stringa.Trova la nonna occorrenza di un carattere in una stringa

Per esempio, il 3 ° occorrenza del carattere 't' nella stringa "dtststxtu" è 5.
(Si noti che la stringa ha 4 t s.)

+0

Che cosa si deve lavorare con così lontano? –

+1

Ho modificato la tua risposta per trasmettere in modo più chiaro ciò che desideri. Spero che otterrai alcune risposte che rispondono alla domanda. Non essere fluente in inglese non è un problema su Stack Overflow, puoi sempre aggiungere una riga per chiedere a qualcuno più fluente di modificare la tua domanda e ripulirla, ma devi sforzarti di fornire alcuni esempi nella domanda in modo che le persone capiscano cosa hai bisogno. –

risposta

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

che potrebbe essere fatto molto più pulito, e non ci sono il controllo delle entrate.

+5

Ottimo approccio. Bello e pulito, facile da leggere, facile da mantenere e prestazioni eccellenti. – Mike

+0

l'amore per i loop come questi, non solo danno prestazioni eccellenti, ma non puoi sbagliare con loro dato che tutto è cristallino e proprio davanti ai tuoi occhi. Scrivi un linq e alcuni sviluppatori lo mettono in un ciclo non comprendendo il costo e tutti continuano a chiedersi dove si trova il collo di bottiglia delle prestazioni. – user734028

11

Aggiornamento: Indice di ennesimo avvenimento one-liner:

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

utilizzare questi a proprio rischio. Sembra un compito a casa, quindi ho lasciato alcuni bug in esso per la tua ricerca:

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

L'esempio one-liner non funziona perché il valore di n non viene mai modificato. –

+2

Bella soluzione, anche se questo non è un vero "one-liner" in quanto una variabile deve essere definita al di fuori dell'ambito del lambda. s.TakeWhile (c => ((n - = (c == 't'))?1: 0)> 0) .Count(); – nullable

+0

-1, "così ho lasciato alcuni bug per trovare" – Zanon

4

La risposta di Joel è buona (e l'ho svalutato). Qui è una soluzione basata su LINQ:

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

@Andrew - puoi abbreviare questo saltando il comando "Dove" e passando il predicato al metodo "Conteggio". Non che ci sia qualcosa di sbagliato in questo modo. –

+9

Questo non troverà solo quante occorrenze di un personaggio ci sono, piuttosto che l'indice dell'ennesimo? – dfoverdx

7

Ecco un'altra soluzione 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); 
} 

Solo per divertimento, ecco una soluzione Regex. Ho visto alcune persone che inizialmente utilizzavano il Regex per contare, ma quando la domanda è cambiata non sono stati apportati aggiornamenti. Ecco come può essere fatto con Regex - di nuovo, solo per divertimento. L'approccio tradizionale è il migliore per semplicità.

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

Ecco un modo per farlo

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

Un'altra soluzione RegEx-based (non testata) divertente:

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

Questo dovrebbe essere un po 'più ottimali che richiedere RegEx per creare un Abbina la raccolta, solo per scartare tutti tranne una partita.

+0

In risposta al commento della raccolta Matches (poiché questo è ciò che avevo mostrato nella mia risposta): suppongo che un approccio più efficiente sarebbe utilizzare un ciclo while per il controllo di 'match.Success' e ottenere' NextMatch' mentre si incrementa un contrastare e interrompere presto quando il contatore == indice'. –

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

Ecco un'implementazione ricorsiva - come un metodo di estensione, mimicing il formato del metodo quadro (s):

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

Inoltre, qui ci sono alcune (MbUnit) unit test che potrebbero aiutarvi (per dimostrare che è corretto):

[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 correttamente commentato che di Joel Coehoorn one-liner non funziona.

Ecco un due liner fa lavoro, un metodo di estensione stringa che restituisce l'indice 0-based del verificarsi ennesima di un personaggio, oppure -1 se non verificarsi ennesima esiste:

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

puoi farlo con le espressioni regolari.

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

migliore riguardo.

16

C'è un errore minore nella soluzione precedente.

Ecco alcuni codice aggiornato:

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

Cosa restituisce se il personaggio non viene trovato? –

+0

Restituisce la lunghezza/conteggio della stringa s. È necessario verificare questo valore. – Yoky

1

Ciao a tutti ho creato due metodi di sovraccarico per la ricerca di occorrenza ennesima di char e per il testo con minore complessità senza la navigazione attraverso loop, che aumentano le prestazioni di la tua applicazione.

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

Dal momento che il built-in IndexOf funzione è già ottimizzato per la ricerca di un carattere all'interno di una stringa, una versione ancora più veloce sarebbe (come metodo di estensione):

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

O per ricercare fine della stringa usando 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; 
} 

Ricerca di una stringa invece di un personaggio è semplice come cambiare il tipo di parametro da char a string e, facoltativamente, aggiungere un sovraccarico per specificare 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

aggiungo un'altra risposta che correre abbastanza veloce rispetto ad altri metodi di

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 Cals' LINQ estese per generico.

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

Alcune prove.

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

se il vostro interessato è anche possibile creare metodi di estensione stringa in questo modo:

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