好的,所以我知道像這樣的問題在這裏已經被問了很多,但我似乎無法讓解決方案起作用。 我想從文件中取一個字符串,並找到該字符串中最長的單詞。 簡單。查找字符串中最長的單詞
我認爲問題在於我是否打電話給string[]
或char[]
或我的方法,當前stringOfWords
返回char[]
。
我試圖然後通過降序長度並獲得第一個值,但在OrderByDescending
方法獲得ArgumentNullException
。
任何輸入非常讚賞。
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);
}
}
}
代碼你」的複雜性已發佈爲「這是我試圖解決問題的地方」看起來不像C#(因爲所有.Net屬性/方法都是大寫)。該代碼應該給你編譯錯誤,而不是... –
對所有變量聲明使用var使得你的代碼不易讀。 –
@MrAnderson這是一個意見問題。 – stuartd