una quitar primer longitud extraer ejemplos comparar caracteres caracter cadenas cadena c# string-matching

quitar - string[] c# ejemplos



Método de comparación de cadenas c#que devuelve el índice de la primera no coincidencia (6)

¿Existe algún método de comparación de cadenas que devuelva un valor basado en la primera aparición de un carácter no coincidente entre dos cadenas?

es decir

string A = "1234567890" string B = "1234567880"

Me gustaría recuperar un valor que me permita ver que la primera vez que se produce una ruptura coincidente es A [8]


Es posible escribir extensión de cadena como

public static class MyExtensions { public static IList<char> Mismatch(this string str1, string str2) { var char1 = str1.ToCharArray(); var char2 = str2.ToCharArray(); IList<Char> Resultchar= new List<char>(); for (int i = 0; i < char2.Length;i++ ) { if (i >= char1.Length || char1[i] != char2[i]) Resultchar.Add(char2[i]); } return Resultchar; } }

Utilízalo como

var r = "1234567890".Mismatch("1234567880");

No es un algoritmo optimizado para encontrar la falta de coincidencia.

Si solo te interesa encontrar el primer desajuste,

public static Char FirstMismatch(this string str1, string str2) { var char1 = str1.ToCharArray(); var char2 = str2.ToCharArray(); for (int i = 0; i < char2.Length;i++ ) { if (i >= char1.Length || char1[i] != char2[i]) return char2[i]; } return ''''c; }



No que yo sepa, pero es bastante trivial:

public static int FirstUnmatchedIndex(this string x, string y) { if(x == null || y == null) throw new ArgumentNullException(); int count = x.Length; if(count > y.Length) return FirstUnmatchedIndex(y, x); if(ReferenceEquals(x, y)) return -1; for(idx = 0; idx != count; ++idx) if(x[idx] != y[idx]) return idx; return count == y.Length? -1 : count; }

Esta es una comparación ordinal simple. La comparación normal entre mayúsculas y minúsculas es un cambio fácil, pero la base cultural es difícil de definir; "Weißbier" no coincide con "WEISSBIERS" en la S final en la segunda cadena, pero ¿eso cuenta como posición 8 o posición 9?


Si tiene instalado .net 4.0, esta podría ser una forma:

string A = "1234567890"; string B = "1234567880"; char? firstocurrence = A.Zip(B, (p, q) => new { A = p, B = q }) .Where(p => p.A != p.B) .Select(p => p.A) .FirstOrDefault();

editar:

Aunque, si necesitas el puesto:

int? firstocurrence = A.Zip(B, (p, q) => new { A = p, B = q }) .Where(p => p.A != p.B) .Select((p, i) => i) .FirstOrDefault();


Un método de extensión a lo largo de las líneas de abajo haría el trabajo:

public static int Your_Name_Here(this string s, string other) { string first = s.Length < other.Length ? s : other; string second = s.Length > other.Length ? s : other; for (int counter = 0; counter < first.Length; counter++) { if (first[counter] != second[counter]) { return counter; } } return -1; }


/// <summary> /// Gets a first different char occurence index /// </summary> /// <param name="a">First string</param> /// <param name="b">Second string</param> /// <param name="handleLengthDifference"> /// If true will return index of first occurence even strings are of different length /// and same-length parts are equals otherwise -1 /// </param> /// <returns> /// Returns first difference index or -1 if no difference is found /// </returns> public int GetFirstBreakIndex(string a, string b, bool handleLengthDifference) { int equalsReturnCode = -1; if (String.IsNullOrEmpty(a) || String.IsNullOrEmpty(b)) { return handleLengthDifference ? 0 : equalsReturnCode; } string longest = b.Length > a.Length ? b : a; string shorten = b.Length > a.Length ? a : b; for (int i = 0; i < shorten.Length; i++) { if (shorten[i] != longest[i]) { return i; } } // Handles cases when length is different (a="1234", b="123") // index=3 would be returned for this case // If you do not need such behaviour - just remove this if (handleLengthDifference && a.Length != b.Length) { return shorten.Length; } return equalsReturnCode; }