如何使用C#从字符串中找到最大的单词?

时间:2011-02-24 03:21:34

标签: c# string

这是我从给定字符串中查找最大单词的代码。我已经得到了字符串中所有单词的长度,现在如何获得要打印出来的最大单词?我试图获得所有最大的单词,但我无法使用此代码PLZ帮助?

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

8 个答案:

答案 0 :(得分:5)

使用Max来获取此

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);
    }
}

答案 1 :(得分:4)

好的,这是一个很好的干净方式,使用LINQ获取字符串列表,并返回最长的列表。 (测试假定为IEnumerable<string>

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

解释:

  1. 我们使用字符串的长度对列表进行分组。这将返回IGrouping,其中包含int类型的键,该键是该组中字符串的长度。
  2. 然后我们订购它们,以便最大的键(字符串长度)位于顶部
  3. 然后我们选择该组。
  4. (可选)将其投影到列表中。您只需在foreach循环中使用此IGrouping,而无需运行ToList()
  5. 享受!

答案 2 :(得分: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]);
        }
    }
}

答案 3 :(得分: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 :(得分: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);

答案 5 :(得分: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()));
}

答案 6 :(得分: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();



        }
    }
}

答案 7 :(得分:0)

看看我的解决方案

它使用Dictionarywordslengths存储在一起

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;
    }