2016-07-20 56 views
2

好的,所以我知道像這樣的問題在這裏已經被問了很多,但我似乎無法讓解決方案起作用。 我想從文件中取一個字符串,並找到該字符串中最長的單詞。 簡單。查找字符串中最長的單詞

我認爲問題在於我是否打電話給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); 
     } 
    } 
} 
+0

代碼你」的複雜性已發佈爲「這是我試圖解決問題的地方」看起來不像C#(因爲所有.Net屬性/方法都是大寫)。該代碼應該給你編譯錯誤,而不是... –

+0

對所有變量聲明使用var使得你的代碼不易讀。 –

+0

@MrAnderson這是一個意見問題。 – stuartd

回答

3

方法ToArray()在這種情況下返回char[]這是單個字符的陣列。但是,你需要一個單獨的單詞陣列。你可以這樣說:

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

而且你必須在你的lambda表達式一個錯字(大寫L):

n => n.Length 
+0

@MartinHeralecký,謝謝,那真是太棒了。用空白分割創建字符串數組對它進行排序。當然,那裏有錯字! –

1

正如其他回答表明,你需要拆分的字符串。

string[] stringOfWords = fileText.split(new Char [] {',' , ' ' }); 
//all is well, now let's loop over it and see which is the biggest 
int biggest = 0; 
int biggestIndex = 0; 

for(int i=0; i<stringOfWords.length; i++) { 
    if(biggest < stringOfWords[i].length) { 
     biggest = stringOfWords[i].length; 
     biggestIndex = i; 
    } 
} 
return stringOfWords[i]; 

我們在這裏做基於空格(」「),或commas-您可以添加分隔符有無限數量的分割線 - 每一個單詞,然後,獲取自己的空間陣列。

從那裏,我們遍歷數組。如果我們遇到比當前最長單詞長的單詞,我們會更新它。

+0

那是不是最長的單詞? – Ares

+0

再次更正。 – Ares

1

試試這個:

var fileText = File.ReadAllText(@"C:\Users\RichardsPC\Documents\TestText.txt"); 
var words = fileText.Split(' ') 
var finalValue = fileText.OrderByDescending(n=> n.Length).First(); 
Console.WriteLine("Longest word: " + finalValue"); 
+0

你是對的!我修好了它 – Kedrzu

1

不要分割字符串,使用正則表達式

如果你關心性能你不想拆分字符串。爲了做到分裂法的原因將不得不遍歷整個字符串創建它找到分裂和把它們放到一個數組,超過N計算成本,然後做一個項目新的字符串您可以通過另一個(至少)O(nLog(n))步驟來完成。

您可以使用正則表達式這一點,這將是更有效,因爲它只會在字符串迭代一次

var regex = new Regex(@"(\w+)\s",RegexOptions.Compiled); 
var match = regex.Match(fileText); 
var currentLargestString = ""; 

while(match.Success) 
{ 
    if(match.Groups[1].Value.Length>currentLargestString.Length) 
    { 
     currentLargestString = match.Groups[1].Value; 
    } 

    match = match.NextMatch(); 
} 

關於這樣做的好處是,你並不需要打破字符串立即進行分析,如果您需要逐漸加載文件是一個相當簡單的更改,只需將該單詞保留在一個對象中並將其稱爲多個字符串即可

如果您在使用陣列不通過迭代

你不需要你只是爲了尋找最大的項目做一個訂單,將訂單計算複雜度在大多數情況下O(nLog(n)),遍歷列表具有O(n)

var largest = ""; 
foreach(var item in strArr) 
{ 
    if(item.Length>largest.Length) 
     largest = item; 
} 
相關問題