查找字符串中最长的单词 [英] Finding longest word in string

查看:59
本文介绍了查找字符串中最长的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我知道像这样的问题在这里已经问了很多,但是我似乎无法使解决方案起作用.我正在尝试从文件中获取一个字符串,并在该字符串中找到最长的单词.简单.

Ok, so I know that questions LIKE this have been asked a lot on here, but I can't seem to make solutions work. I am trying to take a string from a file and find the longest word in that string. Simples.

我认为问题在于我是在 string [] 还是在 char [] 上调用方法,目前 stringOfWords 返回一个 char [] .

I think the issue is down to whether I am calling my methods on a string[] or char[], currently stringOfWords returns a char[].

我试图按长度降序排序并获取第一个值,但是在 OrderByDescending 方法上获取了 ArgumentNullException .

I am trying to then order by descending length and get the first value but am getting an ArgumentNullException on the OrderByDescending method.

非常感谢任何输入.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace TextExercises
{
    class Program
    {
        static void Main(string[] args)
        {
            var fileText = File.ReadAllText(@"C:\Users\RichardsPC\Documents\TestText.txt");
            var stringOfWords = fileText.ToArray();

            Console.WriteLine("Text in file: " + fileText);
            Console.WriteLine("Words in text: " + fileText.Split(' ').Length);

            // This is where I am trying to solve the problem
            var finalValue = stringOfWords.OrderByDescending(n => n.length).First();

            Console.WriteLine("Largest word is: " + finalValue);
        }
    }
}

推荐答案

方法 ToArray()在这种情况下返回 char [] ,它是单个字符的数组.但是,您需要一个由单个单词组成的数组.您可以这样获得它:

Method ToArray() in this case returns char[] which is an array of individual characters. But instead you need an array of individual words. You can get it like this:

string[] stringOfWords = fileText.Split(' ');

您的lambda表达式中有一个错字(大写L):

And you have a typo in your lambda expression (uppercase L):

n => n.Length

这篇关于查找字符串中最长的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆