Замена слова в строке - C#
Формулировка задачи:
Пробую заменить слово в строке вот так
В итоге `some_1 or some-1 or Text use 1, read 1 or what 1?`
Необходимо `some_text or some-text or 1 use 1, read 1 or what 1?`
Как можно исправить? может регулярные выражения? или другой какой способ? Спс
string s = "some_text or some-text or Text use text, read text or what text?";
s = s.Replace("text", "1");Решение задачи: «Замена слова в строке»
textual
Листинг программы
static void Main(string[] args)
{
string oldWord="Text";
string newWord ="1";
string str = "some_text or some-text or Text use text, read text or what text?";
string newStr = string.Join( " ", str.Split().Select(w => w = ReplaseWord(w, oldWord, newWord)) );
Console.WriteLine(" {0} \n {1}", str, newStr);
Console.ReadKey();
}
static string ReplaseWord(string nextWord, string oldWord, string newWord)
{
string punct= string.Empty;
string word = nextWord;
foreach (char ch in nextWord)
{
if (char.IsPunctuation(ch) && ch != '-' && ch != '_')
{
punct = ch.ToString();
word = word.Replace(punct, string.Empty);
}
}
return word.ToLower() == oldWord.ToLower() ? newWord + punct : nextWord;
}