繁体   English   中英

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

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

请帮忙,我不太明白如何在不使用其他库的情况下用代码编写任务。 任务:给定一个字符串,其中包含几个由空格分隔的单词。 需要从字符串中删除由 n 个字母组成的单词。 数字 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));
        }
    }

   
}

在你用空格分割输入字符串后,你得到了字符串数组。 每个字符串都包含.Length属性,您可以过滤掉所有不符合您要求条件的字符串。 然后你只需要在它们之间用“”粘回剩余的字符串。

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

暂无
暂无

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

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