选择字符串上每个单词的前2个字符

问题描述:

我创建了以下功能,但尚未完成。我想返回字符串中每个单词的前2个字符。以下是我迄今为止:选择字符串上每个单词的前2个字符

Function SelectWords(ByVal text As String, ByVal maxWords As Integer) As String 
    If String.IsNullOrEmpty(text) Then Return String.Empty 
    If maxWords <= 0 Then Return String.Empty 

    Dim words As String() = text.Split(" "c) 

    Return String ''I am stuck here 
End Function 

你没有描述maxwords的目的,也不得与a做什么。循环部分:

Dim words = str.Split(" "c) 
Dim ret As New StringBuilder ' in case it is a long string 

For Each w As String In words 
    If w.Length > 1 Then 
     ret.Append(w.Substring(0, 2)) 
    Else 
     ' decide if you want 1 
    End If 

Next 
return ret.toString 

您拥有的代码不会执行您所描述的任何操作。请改用此功能。

Function SelectWords(ByVal text As String, ByVal maxWords As Integer) As String 
    Dim collection As MatchCollection = Regex.Matches(text, "(\w{2})\w*\b") 

    Dim output As New System.Text.StringBuilder 
    Dim counter As Integer = 0 
    For Each M As Match In collection 
     output.Append(M.Groups(1).Value) 
     counter += 1 
     If counter = maxWords Then 
      Exit For 
     End If 
    Next 

    Return output.ToString 
End Function