简体   繁体   中英

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

   
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM