Home > Net >  replacing words
replacing words

Time:12-07

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

CodePudding user response:

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);

CodePudding user response:

// 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.

  • Related