It is necessary to replace the end of all words in the sentence from ed to ing . How to find these words in the string?
2 answers
If the last two letters in the word 'ed' in the word must be replaced by 'ing'
If right in the forehead, as it is possible.
public string[] ReplaceArrayWords(string[] array, string first, string last){ List<string> result = new List<string>(); foreach(string word in array){ if(word.Substring(word.length-first.length,first.length).Equals(first)) result.Add(word.Substring(0,word.length-first.length)+last); else result.Add(word); } return result.ToArray(); } c Framework 4.5+ (as suggested by Alexander Petrov )
public string[] ReplaceArrayWords(string[] array, string first, string last){ List<string> result = new List<string>(); foreach(string word in array){ if(word.EndsWith(first)) result.Add(word.Substring(0,word.length-first.length)+last); else result.Add(word); } return result.ToArray(); } then:
string[] newArray = ReplaceArrayWords(array,"ed","ing"); - Your code can be simplified using String.EndsWith . - Alexander Petrov
- Thank you, I didn’t know such a method, it appeared in 4.5 versions)) - test123
- oneThe method appeared in version 3.5. On the MSDN page, click on "Other Versions" and you will see all the versions where this method is implemented. - Vladimir Zhukov
|
using System.Text.RegularExpressions; string[] words; for (int i = 0; i < words.Length; i++) { words[i] = Regex.Replace(words[i], "(ed)$", "ing"); } - This is not exactly what Dmitry asked. Words are not in an array, but in a string. - Nick Volynkin ♦
- He also said that "Implemented the importation of all the words of a string into an array." - a1bT
- but really. - Nick Volynkin ♦
|
tried->trying- Igorwed->wing- Nick Volynkin ♦