开发者

replacing words

开发者 https://www.devze.com 2022-12-07 17:29 出处:网络
I want to replace the first and last words of the sentence which I typed in the console. if I type the following sentence 开发者_运维问答in console:

I want to replace the first and last words of the sentence which I typed in the console.

if I type the following sentence 开发者_运维问答in console:

London is the Capital of UK.

I need such result

UK is the capital of London.


You could use following method and String.Split + String.Join:

public static void SwapFirstAndLast<T>(IList<T>? items)
{
    if (items == null || items.Count < 2) return;
    T first = items[0];
    items[0] = items.Last();
    items[^1] = first;
}

string sentence = " London is the Capital of UK";
string[] wordDelimiters = { " " };
string[] words = sentence.Trim().Split(wordDelimiters, StringSplitOptions.RemoveEmptyEntries);
SwapFirstAndLast(words);
sentence = string.Join(" ", words);


// Read the sentence from the console
string sentence = Console.ReadLine();

// Split the sentence into words
string[] words = sentence.Split(' ');

// Check if the sentence has at least two words
if (words.Length >= 2)
{
    // Swap the first and last words
    string firstWord = words[0];
    string lastWord = words[words.Length - 1];
    words[0] = lastWord;
    words[words.Length - 1] = firstWord;

    // Rebuild the sentence using the modified words
    string modifiedSentence = string.Join(" ", words);
    Console.WriteLine(modifiedSentence);
}

This code first reads the sentence from the console, then splits the sentence into individual words using the Split method. It then checks if the sentence has at least two words, and if so, it swaps the first and last words and rebuilds the sentence using the modified words.


In more generic case when we should take punctuation into account, e.g.

   London, being a vast area, is the capital of UK =>

=> UK, being a vast area, is the capital of London

we can use regular expressions to match words. Assuming that word is a sequence of letters and apostrophes we can use

[\p{L}']+

pattern and do the following:

using System.Text.RegularExpressions;

...

string text = "London, being a vast area, is the capital of UK";

// All words matched
var words = Regex.Matches(text, @"[\p{L}']+");

// Replace matches: first into last, 
// last into first, all the others keep intact
int index = -1;

var result = Regex.Replace(
    text,
  @"[\p{L}']+",
    m => {
       index += 1;

       if (index == 0)
         return words[^1].Value;
       if (index == words.Count - 1)
         return words[0].Value;
       return m.Value;
    });
``
0

精彩评论

暂无评论...
验证码 换一张
取 消