Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
C# hace muchos reemplazos a la vez en una cadena

Tengo un diccionario de reemplazos.

 var substitutions = new Dictionary<string, string>() { { "one", "two" }, { "two", "three" }, };

Quiero convertir la cadena "uno dos tres cuatro" en "dos tres tres cuatro".

Ejecutar cualquier tipo de cadena de reemplazo iterativa como

 var phrase = "one two three four"; substitutions.Aggregate(phrase, (current, substitution) => current.Replace(substitution.Key, substitution.Value)));

o

 var sb = new StringBuilder(phrase); foreach (var entry in substitutions) { sb.Replace(entry.Key, entry.Value); } sb.ToString();

produce "tres tres tres cuatro" porque el segundo reemplazo "dos" → "tres" puede ver la salida "uno" → "dos" de la salida anterior.

¿Cómo puedo reemplazar solo palabras "originales"?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Divida la cadena en términos individuales, ahora puede iterar solo una vez y reemplazar:

 var phrase = "one two three four"; var terms = phrase.Split(); for(int i = 0; i < terms.Length; i++) { if(substitutions.ContainsKey(terms[i])) { terms[i] = substitutions[terms[i]]; } } phrase = string.Join(" ", terms);
over 4 years ago · Santiago Trujillo Report

0

Podrías usar expresiones regulares de la siguiente manera:

 var substitutions = new Dictionary<string, string>() { { "one", "two" }, { "two", "three" }, }; var phrase = "one two three four"; var pattern = string.Join("|", substitutions.Keys.Select(Regex.Escape)); // Pattern is: one|two var result = Regex.Replace(phrase, pattern, match => substitutions[match.Value]);

ejemplo de trabajo


Si las sustituciones solo deben coincidir con palabras completas, puede actualizar pattern para incluir límites de palabras \b :

 substitutions.Keys.Select(x => @$"\b{Regex.Escape(x)}\b")

ejemplo de trabajo

over 4 years ago · Santiago Trujillo Report

0

Dado que siempre son palabras sueltas divididas por espacio, simplemente divida la cadena y recorra esa colección para reconstruir el nuevo resultado

 var substitutions = new Dictionary<string, string>() { { "one", "two" }, { "two", "three" }, }; var phrase = "one two three four"; // convert to list of words var words = phrase.Split(new[] { " " }, StringSplitOptions.None).ToList(); // keep the transformed result var result = new StringBuilder(); // for each words foreach (var word in words) { // add a space before since we removed it. // will trim later on for the first useless space it creates result.Append(" "); // to get the dictionary value string substitutionWord; // if we found the dictionary key if (substitutions.TryGetValue(word, out substitutionWord)) { // add substitution word instead result.Append(substitutionWord); } else // not found { // keep the original word result.Append(word); } } var finalResult = result.ToString().Trim();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!