简体   繁体   English

如何从字符串中删除 n 个字母的单词? c#

[英]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.需要从字符串中删除由 n 个字母组成的单词。 The number n is set by the user.数字 n 由用户设置。

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.每个字符串都包含.Length属性,您可以过滤掉所有不符合您要求条件的字符串。 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: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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