开发者

Find shortest ,average and longest text length in text box in visual basic

开发者 https://www.devze.com 2023-02-28 10:31 出处:网络
what is the code for finding th开发者_开发技巧e shortest,average and longest sentence form the text boxNot sure exactly what you are asking, but taking a shot anyway. You can split the text on \'.\' a

what is the code for finding th开发者_开发技巧e shortest,average and longest sentence form the text box


Not sure exactly what you are asking, but taking a shot anyway. You can split the text on '.' and then use LINQ to figure out the elements which satisfies those criteria.


Well I guess the best way to do this would be to split up the text in the textbox with something like:

Dim sSplitString As String() = TextBox1.Text.Split(New Char() {"."c})

Dim sBigSentence As String = String.Empty
Dim sSmallSentence As String = sSplitString(0)

For Each sVal As String In sSplitString
  'Figure out the big sentence
  If sVal.Length > sBigSentence.Length Then
    sBigSentence = sVal
  End If

  'Figure out the small sentence, you might also need to check and make sure the 
  ' the last value doesn't have a blank string.
  If sVal.Length < sSmallSentence.Length Then
    sSmallSentence = sVal
  End If

  'Average Sentence...
Next

I haven't tested this, but it should be something like this. I'll let you figure out the average sentence part :P


// Something like this should work, remember you might have to trim
// testing for Max
// this is done in linqpad, hence the .Dump();


string txt = "This is the first sentence. Another one. Short";

var sentences = txt.Split('.').ToList();

var result = from s in sentences
             let max = sentences.Max(st=>st.Length)
             where s.Length == max
             select s;

result.Dump();


    Dim txtInput As String = "This is a test. This is also a test.  LONGWORDHERE?  This works too!"
    Dim Punctuation As Char() = {"?"c, "!"c, "."c, ";"c}

    Dim Sentences = (From mySent In txtInput.Split(Punctuation))

    Dim Avg As Double = Sentences.Average(Function(w) w.Length)
    Dim Max As Integer = Sentences.Max(Function(w) w.Length)
    Dim Min As Integer = Sentences.Min(Function(w) w.Length)

I think that is your best bet. There are lots of way to skin a cat, but I think that is fairly easy to read and should be reasonably fast, at least, depending on the size of the text you are working with.

This will only work for the punctuation shown and it will include white space in the character count.

EDIT: You'd want to get the minimum that is greater than zero in length. So, that line would become...

Dim Min As Integer = (From mySent In txtInput.Split(Punctuation) Where mySent.Length > 0).Min(Function(w) w.Length)

I don't know what you mean when you say 'full-stop'. Is that a return line?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号