Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

c# - Finding longest word in string

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.

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

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

Any input much appreciated.

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:UsersRichardsPCDocumentsTestText.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);
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(' ');

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

n => n.Length

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...