2014-10-19 3 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 
관련 문제