這是我找到給定字符串中最大單詞的代碼。我已經得到了字符串中所有單詞的長度,現在如何獲得要打印的最大單詞?我試圖得到所有最大的單詞,但我無法使用此代碼plz幫助嗎?如何使用C#從字符串中找到最大的單詞?
using System;
using System.Linq;
class largest1{
public void largest(){
Console.WriteLine("Enter the String:");
string buffer1 = Console.ReadLine();
string[] buffer = buffer1.Split(' ');
int length;
string largestword = buffer[0];
for(int i = 0; i < buffer.Length; i++){
string temp = buffer[i];
length = temp.Length;
if(largestword.Length < buffer[i].Length) {
largestword = buffer[i];
}
}
var largestwords = from words in buffer
let x = largestword.Length
where words.Length == x
select words;
Console.Write("Largest words are:");
foreach(string s in largestwords){
Console.Write(s);
}
}
static void Main(){
largest1 obj = new largest1();
obj.largest();
}
}
@spidy對不起另一種解決方案來編輯當u正在回覆..有什麼兩樣東西是錯誤的代碼? – Beginner 2011-02-24 05:45:26
這是最新的錯誤。當你做第二個循環時,buffer3將這個單詞存儲在索引i處。 所以想象你的話是「這」「是」「四」「長」。最長的單詞是「This」(長度爲4個字符),「four」和「long」長度相同。當你第二次循環時,你在索引0處存儲「This」,在索引2存儲「4」,在索引3存儲「long」。索引1處沒有存儲,因爲「is」的長度與最長的詞。你需要兩個索引變量。 在循環外部添加int j = 0。並在if語句中添加j ++。 – Spidy 2011-02-24 05:47:49
即 「對於列表中的詞,其中words.length == largestword.length選擇詞;」 也可以工作 – Spidy 2011-02-24 05:54:21