Home > Blockchain >  How do I remove a dot from a specific string?
How do I remove a dot from a specific string?

Time:09-15

    Console.WriteLine("Write three words with a point in the end");

    var ord = Console.ReadLine().Split(' ');
    string a = ord[0];
    string b = ord[1];
    string c = ord[2];

    Console.WriteLine(c " " b " " a ".")

So what I am trying to do is have these three words (a,b,c) in oppisite order and with a dot in the end. So Im trying to reomve the dot after string c and then add one after a. But can't figure out how.

CodePudding user response:

You can either:

  1. Trim the dot before splitting:

    var ord = Console.ReadLine().TrimEnd('.').Split(' ');
    
  2. Use the same variable instead of a new one (clean)

    c = c.TrimEnd('.')
    

CodePudding user response:

Your code is pretty close:

  • you're splitting the sentence into an array of words
  • you're selecting the first three array elements (first three words)
  • you're printing the three words in reverse order, and concatenating a period

The only step that's missing is removing the . from the end of the user's input. That can be done in several ways:

The sample of what you tried looks like it should work -- perhaps you forgot to update your Console.WriteLine() call to use clean instead of c?

string clean = c.Replace('.', string.Empty);
Console.WriteLine(clean   " "   b   " "   a   ".");

Removing the last character from ord prior to splitting it is another option, something like:

var noDot = ord.Substring(0, ord.Length - 1);
// (and then splitting `noDot`)

Or removing all .'s from the input:

var ord = Console.ReadLine().Replace('.', string.Empty).Split(' ');

And you could also exploring doing this declaratively with LINQ

string input = "one two three four.";
var reversedThree = input.Replace(".", string.Empty).Split(' ').AsQueryable().Take(3).Reverse();
Console.WriteLine($"{string.Join(" ", reversedThree)}.");
  • Related