2014-10-19 6 views
0

Я создал следующую функцию, но не смог закончить. Я хочу вернуть первые 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 

ответ

1

Вы не описали цели 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 
1

Код, который у вас есть, не делает ничего, что вы описываете. Вместо этого попробуйте эту функцию.

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 
Смежные вопросы