【发布时间】:2011-08-12 13:57:18
【问题描述】:
从文本框中查找最短、平均和最长句子的代码是什么
【问题讨论】:
-
这是stackoverflow.com/questions/6090462/…的完全相同的副本
从文本框中查找最短、平均和最长句子的代码是什么
【问题讨论】:
不知道你在问什么,但还是试一试。您可以拆分“。”上的文本。然后使用 LINQ 找出满足这些条件的元素。
【讨论】:
好吧,我想最好的方法是将文本框中的文本拆分为:
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
我还没有测试过这个,但它应该是这样的。我会让你算出平均句子部分: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)
我认为这是你最好的选择。有很多方法可以给猫剥皮,但我认为这很容易阅读,并且应该相当快,至少取决于您正在处理的文本的大小。
这仅适用于显示的标点符号,它会在字符数中包含空格。
编辑:您希望获得长度大于零的最小值。所以,那条线会变成……
Dim Min As Integer = (From mySent In txtInput.Split(Punctuation) Where mySent.Length > 0).Min(Function(w) w.Length)
我不知道您所说的“句号”是什么意思。那是回线吗?
【讨论】: