gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:07:29 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于c# - 如何使用 C# 从字符串中找到最大的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5100019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com