簡體   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