2011-02-24 69 views
3

這是我找到給定字符串中最大單詞的代碼。我已經得到了字符串中所有單詞的長度,現在如何獲得要打印的最大單詞?我試圖得到所有最大的單詞,但我無法使用此代碼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(); 
    } 
} 
+0

@spidy對不起另一種解決方案來編輯​​當u正在回覆..有什麼兩樣東西是錯誤的代碼? – Beginner 2011-02-24 05:45:26

+0

這是最新的錯誤。當你做第二個循環時,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

+0

即 「對於列表中的詞,其中words.length == largestword.length選擇詞;」 也可以工作 – Spidy 2011-02-24 05:54:21

回答

3
//Put this in your class so that it is persisted 
string largestword = ""; 

//Put this right before your for loop 
largestword = buffer[0]; 

//Put this inside your for loop 
if(largestword.Length < buffer[i].Length) { 
    largestword = buffer[i]; 
} 

編輯:增加了對相同長度的多個單詞支持

class LargestWordsClass 
{ 
    public LargestWordsClass() 
    { 
     _LargestWords = new List<String>(); 
    } 

    //This says that the variable can be set from the class but read by anyone 
    public int LargestWordSize 
    { 
     get; 
     private set; 
    } 

    //This lets users get the list without being able to modify it 
    private List<String> _LargestWords; 
    public String[] LargestWords 
    { 
     get 
     { 
      return _LargestWords.ToArray(); 
     } 
    } 

    public void FindLargestWord() 
    { 
     _LargestWords.Clear(); 

     Console.WriteLine("Enter the String: "); 
     String buffer = Console.ReadLine(); 
     String[] splitBuffer = buffer.Split(' '); 

     LargestWordSize = 0; 
     for (int i = 0; i < splitBuffer.Length; i++) 
     { 
      if (LargestWordSize < splitBuffer[i].Length) 
      { 
       LargestWordSize = splitBuffer[i].Length; 
       _LargestWords.Clear(); 
       _LargestWords.Add(splitBuffer[i]); 
      } 
      else if (LargestWordSize == splitBuffer[i].Length) 
      { 
       _LargestWords.Add(splitBuffer[i]); 
      } 

      Console.WriteLine("The word is " + splitBuffer[i] + " and the length is " + splitBuffer[i].Length.ToString()); 
     } 

     Console.WriteLine("The largest word" + ((_LargestWords.Count > 1) ? "s are" : " is:")); 
     for (int i = 0; i < _LargestWords.Count; i++) 
     { 
      Console.WriteLine(_LargestWords[i]); 
     } 
    } 
} 
+0

@ Spidy謝謝你的工作 – Beginner 2011-02-24 03:32:56

+0

沒問題。你近距離 – Spidy 2011-02-24 03:35:04

+0

如果兩個單詞有相同的長度會怎麼樣?我必須能夠打印這兩個詞? – Beginner 2011-02-24 03:54:53

5

使用最多得到這個

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

public class MainClass { 
    public static void Main() { 
     string[] words = { "cherry", "apple", "blueberry" }; 

     int longestLength = words.Max(w => w.Length); 

     Console.WriteLine("The longest word is {0} characters long.", longestLength); 
    } 
} 
+0

這不會打印所有的單詞或顯示最長的單詞 – Spidy 2011-02-24 03:36:08

+0

@spidy:好的,我同意。你給了他正確的答案。但這是獲得最大詞彙長度的更優雅的方式。然後你可以做任何事情。 – ayush 2011-02-24 03:56:31

+0

如果2個單詞具有相同的長度會怎樣? – Beginner 2011-02-24 03:59:59

0

試試這個

public void largest(){ 

Console.WriteLine("Enter the String:"); 
string buffer1 = Console.ReadLine(); 
string[] buffer = buffer1.Split(' '); 
    int length; 
    /*foreach (string word in buffer) 
    { 
    //Console.WriteLine(word); 
    }*/ 
     string temp = string.Empty; 
    for(int i = 0; i < buffer.Length; i++){ 
     if(temp.length = buffer[i].length) 
      temp = buffer[i];   
} 
Console.WriteLine("The word is " + temp + " and the length is " + temp.length.tostring()); 

} 
4

Alrighty,這裏是一個很好的清理方式,使用LINQ獲取字符串列表,並返回最長列表。 (測試假定爲IEnumerable<string>

 var ordered = test 
      .GroupBy(str => str.Length) 
      .OrderByDescending(grp => grp.Key) 
      .First() 
      .ToList(); 

的解釋:

  1. 我們組使用字符串的長度名單這將int類型的關鍵是長度返回IGrouping該組中的字符串
  2. 的。然後,我們命令他們這樣的大鍵(字符串長度)在頂部
  3. 然後,我們選擇該組。
  4. (可選)將其投影到列表中。您只需在foreach循環中使用此IGrouping而無需運行ToList()

享受!

+0

我已經通過以下ur技術編輯了代碼plz幫助我? – Beginner 2011-02-24 05:43:17

+0

@ user561730:我不確定你的意思。隨意使用我給你的確切代碼。 – 2011-02-24 05:52:46

+0

現在這個問題已經使用你的想法進行編輯,你能看到我犯了什麼錯誤嗎? – Beginner 2011-02-24 06:14:09

0

試試這個:

string[] words = { "berryblue", "cherry", "apple", "blueberry" }; 
int maxLength = words.Max(s => s.Length); 
var longestWords = from word in words where word.Length == maxLength select word; 
foreach (var word in longestWords) System.Console.WriteLine(word); 
0

簡明LINQ版本:

static void Main(string[] args) 
{ 
    Console.WriteLine("Enter the string:"); 
    string[] words = Console.ReadLine().Split(' '); 
    var longestWords = words 
     .Where(w => w.Length == words.Max(m => m.Length)); 
    Console.WriteLine("Longest words are: {0}", 
     string.Join(", ", longestWords.ToArray())); 
} 
0
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Testingstring 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string s,s2; 
      s2 = " "; 
      char[] a = new char[]{' '}; 
      Console.WriteLine("Enter any string"); 
      s = Console.ReadLine(); 

      foreach (string s1 in s.Split(a)) 
      { 
       if (s2.Length < s1.Length) 
       { 
        s2 = s1; 
       } 
      } 
      Console.WriteLine("The largest string is " + s2 +" and its length is " +s2.Length); 
      Console.ReadKey(); 



     } 
    } 
} 
+0

歡迎來到計算器!提供示例代碼的簡短說明總是更好,以提高發布準確性:) – 2012-10-29 02:08:50

0

採取看看我的解決方案

它採用了Dictionary存儲words與有lengths

class Program 
{ 
    static void Main(string[] args) 
    { 
     var longestWord = LongestWord("Hello Stack Overflow Welcome to Challenge World"); 

     PrintTheLongestWord(longestWord.Key); 

    } 

    public static KeyValuePair<string, int> LongestWord(String statement) 
    { 
     Dictionary<string, int> wordsLengths = InitializeDictionary(statement.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)); 

     return GetMax(wordsLengths); 
    } 

    private static Dictionary<string, int> InitializeDictionary(string[] wordsList) 
    { 
     Dictionary<string, int> wordsLengths = new Dictionary<string, int>(); 

     foreach (var word in wordsList) 
     { 
      wordsLengths[word] = word.Length; 
     } 

     return wordsLengths; 
    } 

    private static KeyValuePair<string, int> GetMax(Dictionary<string, int> dictionary) 
    { 
     KeyValuePair<string, int> max = new KeyValuePair<string, int>(" ", Int32.MinValue); 
     foreach (var item in dictionary) 
     { 
      if (item.Value.CompareTo(max.Value) > 0) 
       max = item; 
     } 
     return max; 
    }   

    public static void PrintTheLongestWord(string word) 
    { 
     Console.WriteLine($"the Longest word is {word} with length {word.Length}"); 
    } 
} 

這裏是one loop

public static string LongestWord2(String statement) 
    { 
     string max = ""; 
     foreach (string word in statement.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)) 
     { 
      if (word.Length>max.Length) 
      { 
       max = word; 
      } 
     } 
     return max; 
    } 
相關問題