Min-Max_Reid
Min-Max_Reid

Reputation: 1

How to remove n-letter words from a string? In c#

Please help, I don't quite understand how to write a task in code without using additional libraries. Task: given a string containing several words separated by spaces. It is necessary to remove words consisting of n letters from the string. The number n is set by the user.

using System;
using System.Collections.Generic;
using System.Text;

namespace project
{
    class Program
    {
        public static string Func(string text, string n)
        {
            string[] arr = text.Split(' ');
           
            text = text.Replace(text, n);
            return text;

        }
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the number of letters in the word: ");
            int n = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("\nEnter the string: ");
            string text=Console.ReadLine();
            Console.WriteLine($"A string that does not contain a word with {n} letters");
            Console.WriteLine(Func(text,n));
        }
    }

   
}

Upvotes: 0

Views: 38

Answers (1)

Sergey Sosunov
Sergey Sosunov

Reputation: 4600

After you splitted the input string by spaces you got the array of strings. Every string contains .Length property, and you can filter out all the strings that do not match your required conditions. Then you just need to glue back the remaining strings with " " between them.

using System;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        public static string Func(string text, int n)
        {
            var filteredArray = text
                .Split(' ')
                .Where(x => x.Length != n);
            return string.Join(" ", filteredArray);
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Enter the number of letters in the word: ");
            int n = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("\nEnter the string: ");
            string text = Console.ReadLine();
            Console.WriteLine($"A string that does not contain a word with {n} letters");
            Console.WriteLine(Func(text, n));
        }
    }
}

Output:

Enter the number of letters in the word:
6

Enter the string:
Task: given a string containing several words separated by spaces
A string that does not contain a word with 6 letters
Task: given a containing several words separated by

Upvotes: 1

Related Questions