c# - 在没有拆分、不同和 foreach 的情况下查找字符串中最长的单词(并将其写出来)
问题描述
我得到了一项任务,要制定一种方法来查找字符串中最长的单词,而无需拆分、不同和 foreach。
我能够拆分单词并计算长度,但我被困在如何实际比较和写出它们。
static void Main(string[] args)
{
String s1 = "Alex has 2 hands.";
longestWord(s1);
Console.
}
static void longestWord(String s1)
{
char emp = ' ';
int count = 0;
char[] ee = s1.ToCharArray();
for (int i = 0; i < ee.Length; i++)
{
if (ee[i] == emp || ee[i] == '.')
{
count++;
Console.Write(" " + (count-1));
Console.WriteLine();
count = 0;
}
else
{
Console.Write(ee[i]);
count++;
}
}
}
现在的输出如下所示:
Alex 4
has 3
2 1
hands 5
我很确定我只能通过将重置前的计数与 temp int 进行比较来获得最长的数字,但如何用它写出单词。
或者,如果有更简单的方法可能是。
解决方案
你已经走在了一条好路上。不是直接打印单词,而是存储最长单词的长度和位置,并在末尾打印。像这样:
static void longestWord(String s1)
{
char emp = ' ';
int longestLength = 0;
int longestStart = 0;
int currentStart = 0;
for (int i = 0; i < s1.Length; i++)
{
if (s1[i] == emp || s1[i] == '.')
{
// calculate the current word length
int currentLength = i - currentStart;
// test if this is longer than the currently longest
if(currentLength > longestLength)
{
longestLength = currentLength;
longestStart = currentStart;
}
// a new word starts at the next character
currentStart = i + 1;
}
}
// print the longest word
Console.WriteLine($"Longest word has length {longestLength}: \"{s1.Substring(longestStart, longestLength)}\"");
}
没有必要.ToCharArray()
。您可以直接访问字符串。
推荐阅读
- angular - 嵌套的 Mat-Table 内联编辑 - 数据绑定问题
- javascript - TypeScript 增强窗口在单独的文件中不起作用
- c++ - VS 代码未从 Linux 上的 vcpkg 检测库(opencv)。我怎样才能链接它?
- html - 解决 VS Code 中的 CSS 换行问题
- sql-server - 在源表中添加列时 cdc.ddl_history 表中出现错误
- flutter - 术语“Unblock-File”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称
- java - 通过在java中提供年份来确定下一个夏令时
- apache-flink - Flink:如何使用键控状态?
- c# - 我运行网站时没有显示我的流派
- math - 缩小一个圆圈以匹配另一个圆圈所需的比例值?