简体   繁体   English

如何确定文本框中的字符串最长的行

[英]How to determine which line is longest by string in textbox

Trying to find the longest line by string in a textbox (multi-line). 尝试在文本框(多行)中按字符串查找最长的行。 Longest will return the number of the line, for example: 最长将返回行号,例如:

line 1: good day, world
line 2: good evening world
line 3: good morning, world

the longest string found in textbox will return the number of the line which is line 3 something like MessageBox("MAX: 3") or show multiple lines if found same string. 在文本框中找到的最长字符串将返回第3行的行号,类似于MessageBox("MAX: 3")如果找到相同的字符串,则显示多行。

Note: count " " space too. 注意:也要计算空格。

so far i tried this way: 到目前为止,我尝试过这种方式:

string[] stringArray = textBox1.Text.Split(' ');
var  Maximum = "";
var Minimum = textBox1.Lines[0];
foreach (string line in textBox1.Lines)
{
      int index = line.IndexOf(textBox1.Text);
      if (index > 0)
      { 
          if (Minimum.Length > line.Length)
          {
              Minimum = line;
          }

          if (Maximum.Length < line.Length)
          {
              Maximum = line;

           }
           MessageBox.Show(string.Format("MAX: {0} ", index));
       }

but for some reason it won't show it. 但由于某种原因,它不会显示出来。 Any idea why? 知道为什么吗?

Your code splits the text of the textbox at spaces - you get "words". 您的代码在空格处分割文本框的文本-您得到“单词”。 Then you foreach over all lines. 然后,您遍历所有行。 Somehow you search the full text of your box inside of one line of the splitted text of your box. 不知怎的,您搜索框的盒子里装的分裂一行文本内的全文 This can not work unless your textbox contains only 1 line without any newlines in it but then the whole thing does not make any sense anymore. 除非您的文本框仅包含1行,其中没有任何换行符,否则这将无法工作,但是整个事情不再有意义了。

Use textBox1.Lines and check all lines for lenght, use the longest: 使用textBox1.Lines并检查所有行的长度,使用最长的:

int i = 0;
int maxLen = -1;
int maxIndex = - 1;
foreach (var l in textBox1.Lines)
{
    if (l.Length > maxLen)
    {
        maxLen = l.Length;
        maxIndex = i;
    }
    i++;
}
// this will only capture the first line if multiple are same length
// maxLen holds the length of the longest line, maxIndex the index of it

If you want it fancier, use Linq: 如果您想使用它,请使用Linq:

You can use IEnumerable<T>.Select() for that - it has an overload that gives you the index as well. 您可以为此使用IEnumerable<T>.Select() -它有一个重载,也为您提供了索引。 You create an anonymous type, OrderByDescending() it accordingly, get the Max() value from it and sort out Where() the length has this max value - you could shorten it without anonymous type but I think this way its clearer what happens: 您创建一个匿名类型, 相应地创建OrderByDescending() ,从中获取Max()值 ,并找出其中的长度具有此最大值的Where() -您可以在没有匿名类型的情况下将其缩短,但我认为这样可以更清楚地了解发生了什么:

using System;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        string[] stringArray = new[] { // you get this array from Textbox.Lines
            "one line of text",
            "second line with more text",
            "short line",
            "very long line with text and more text",
            "very long line with text and more text" };

        var sorted = stringArray
            .Select((text, index) => new {Index=index, Text=text, Length=text.Length })
            .OrderByDescending(ano => ano.Length)
            .ToList(); // order by lenght descending
        var maxLength = sorted.Max(ano => ano.Length); // get max length

        var maxOnes = sorted.Where(ano => ano.Length == maxLength);

        foreach (var ano in sorted)
            Console.WriteLine(
                $"{ano.Index} has length {ano.Length} and text of '{ano.Text}'");

        Console.WriteLine(
            $"The longest ones had indexes: {string.Join(",",
                                             maxOnes.Select(ano => ano.Index))}");
        Console.ReadLine();
    }
}

Output: 输出:

3 has length 38 and text of 'very long line with text and more text'
4 has length 38 and text of 'very long line with text and more text'
1 has length 26 and text of 'second line with more text'
0 has length 16 and text of 'one line of text'
2 has length 10 and text of 'short line'
The longest ones had indexes: 3,4

Keeping things simple, this should do the job: 保持简单,这应该可以完成工作:

Int32 index = 0;
Int32 maxLength = 0;

String[] lines = textBox1.Lines;

for (Int32 i = 0; i < lines.Length; ++i)
{
    Int32 currLength = lines[i].Length;

    if (currLength > maxLength)
    {
        maxLength = currLength;
        index = i;
    }
}

MessageBox.Show(String.Format("MAX: {0}", index));

Alternatively, using LINQ and OrderByDescending together with IndexOf , you can proceed with the following code: 或者,将LINQ和OrderByDescendingIndexOf一起使用,可以继续执行以下代码:

Int32 index = textBox1.Lines.IndexOf(textBox1.Lines.OrderByDescending(x => x.Length).First());
MessageBox.Show(String.Format("MAX: {0}", index));

Using LINQ will make this easy. 使用LINQ将使此操作变得容易。 Just order the lines by their length and use the last one because the longest will be at the end. 只需按行的长度排序并使用最后一行,因为最长的将在末尾。

var lines = textBox1.Lines.ToList();
var longest = lines.OrderBy(line => line.Length).Last();
var index = lines.IndexOf(longest);

try Orderby and where: 试试Orderby以及哪里:

        var stringOrdered = textBox1.Lines.OrderByDescending(t => t.Length);
        var mostLargeStrings = stringOrdered.Where(str=> str.Length == stringOrdered.First().Length);             
        var index = 0;
        foreach(var TXT in mostLargeStrings)
        {
            index = Array.IndexOf(textBox1.Lines, TXT, index+1);
            MessageBox.Show(string.Format("MAX: {0} ",index));
        }

the code, first order the text strings from the longest to the shortest and then take the ones with the same length as the first one, then we search for their index in textbox Lines 代码,首先将文本字符串从最长到最短排序,然后采用与第一个字符串相同的长度,然后在文本框中搜索它们的索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM