LuLz
LuLz

Reputation: 3

Split a long string by two spaces and output each as new lines

I have a string like

Dim theText As String = "Visual Basic is a legacy third generation event driven programming language and integrated development environment (IDE) from Microsoft."

Now I want to split the string by two spaces and output each as a new line. For example like

Visual Basic
is a
legacy third
generation event
driven programming
language and
integrated development
environment (IDE)
from Microsoft.

I tried to work this out using the following code but doesn't seem to work like I need it to.

Dim LineLength As Integer = 3
    Dim currPos As Integer
    Dim theText As String = "Visual Basic is a legacy third generation event driven programming language and integrated development environment (IDE) from Microsoft."
    Dim thisLine As String
    Dim allLines As New StringBuilder()
    While theText.Length > LineLength
        currPos = theText.IndexOf(" ", LineLength)
        If currPos > -1 Then
            thisLine = theText.Substring(0, currPos + 1)
            theText = theText.Remove(0, currPos + 1)
            allLines.Append(thisLine)
            allLines.Append(vbCrLf)
        End If
    End While
    allLines.Append(theText)
    TextBox2.Text = allLines.ToString()

Any way to achieve this?

Upvotes: 0

Views: 1866

Answers (4)

Litisqe Kumar
Litisqe Kumar

Reputation: 2564

Dim count As Integer = 0
Dim Text As String = "Visual Basic  is a  legacy third  generation event  driven programming  language and  integrated development  environment (IDE)  from Microsoft."
Dim words As String() = Regex.Split(Text, " ")
For Each word As String In words
    count = count + 1
    Response.Write(word & " ")
    If count = 2 Then
        Response.Write("</br>")
        count = 0

    End If
Next

Upvotes: 0

dbasnett
dbasnett

Reputation: 11773

Using the .Split and .Join methods gives this:

    Dim theText As String = "Visual Basic  is a  legacy third  generation event  driven programming  language and  integrated development  environment (IDE)  from Microsoft."

    Dim parts() As String = theText.Split(New String() {"  "}, StringSplitOptions.None)
    TextBox2.Text = String.Join(Environment.NewLine, parts)

Be careful when copying / pasting the above. The double spaces might be converted to a single space in theText.

edit: If the intent was to break on every other space then:

    Dim theText As String = "Visual Basic is a legacy third generation event driven programming language and integrated development environment (IDE) from Microsoft."
    Dim parts() As String = theText.Split(New Char() {" "c})

    Dim sb As New System.Text.StringBuilder
    For x As Integer = 1 To parts.Length - 1 Step 2
        sb.AppendFormat("{0} {1}{2}", parts(x - 1), parts(x), Environment.NewLine)
    Next
    If parts.Length Mod 2 = 1 Then sb.AppendFormat("{0}{1}", parts(parts.Length - 1), Environment.NewLine)

As a function:

Public Function StringToLines(theString As String, _
                              Optional wordsPerLine As Integer = 3, _
                              Optional splitOn As Char() = Nothing) As String

    Dim spltChrs As Char() = New Char() {" "c}
    If splitOn IsNot Nothing Then
        spltChrs = splitOn
    End If

    Dim words() As String = theString.Split(spltChrs, StringSplitOptions.RemoveEmptyEntries)

    Dim sb As New System.Text.StringBuilder
    Dim lines As Integer = 0

    For Each w As String In words
        sb.Append(w)
        sb.Append(" ")
        lines += 1
        If lines >= wordsPerLine Then
            sb.AppendLine()
            lines = 0
        End If
    Next

    Do While sb(sb.Length - 1) = ControlChars.Cr OrElse sb(sb.Length - 1) = ControlChars.Lf OrElse sb(sb.Length - 1) = " "
        sb.Remove(sb.Length - 1, 1)
    Loop
    Return sb.ToString
End Function

Upvotes: 1

JohnKiller
JohnKiller

Reputation: 2008

Original answer:

    Dim inputstr As String = "Visual Basic is a legacy third generation event driven programming language and integrated development environment (IDE) from Microsoft."
    Dim inarray As String() = inputstr.Split(" ")
    Dim outarray As New List(Of String)
    Dim maxiteration As Integer = inarray.Length - 1
    For i As Integer = 0 To maxiteration Step 2
        If i = maxiteration Then
            outarray.Add(inarray(i)) 'if words count is odd
        Else
            outarray.Add(inarray(i) & " " & inarray(i + 1))
        End If
    Next
    Dim outstr = String.Join(vbCrLf, outarray)

Improved answer:

Function StringBreak(ByVal input As String, Optional ByVal wordsPerRow As Integer = 2) As String
    Dim inarray As String() = input.Split(" ")
    Dim outstr As String = inarray(0)
    For i As Integer = 1 To inarray.Length - 1
        If i Mod wordsPerRow = 0 Then
            outstr &= vbCrLf & inarray(i)
        Else
            outstr &= " " & inarray(i)
        End If
    Next
    Return outstr
End Function

Dim result = StringBreak("Visual Basic is a legacy third generation event driven programming language and integrated development environment (IDE) from Microsoft.", 3)

Use the last parameter to set the word count per line.

Upvotes: 3

Ross Presser
Ross Presser

Reputation: 6255

' original poster's original string. 
' note, SINGLE SPACES were specified, not double spaces.
Dim theText As String = "Visual Basic is a legacy third generation event driven programming language and integrated development environment (IDE) from Microsoft."

' regular expression built using Expresso
' will match a word plus a space plus a word, then break on the second space encountered

'  Regular expression built for Visual Basic on: Sat, Jun 27, 2015, 11:34:11 AM
'  Using Expresso Version: 3.0.4750, http://www.ultrapico.com
'  
'  A description of the regular expression:
'  
'  [1]: A numbered capture group. [[^ ]+ [^ ]+]
'      [^ ]+ [^ ]+
'          Any character that is NOT in this class: [ ], one or more repetitions
'          Space
'          Any character that is NOT in this class: [ ], one or more repetitions
'  Space, zero or one repetitions
'  
'

Dim regex As Regex = New Regex( _
      "([^ ]+ [^ ]+) ?", _
    RegexOptions.CultureInvariant _
    Or RegexOptions.Compiled _
    )


' match the string against the regex

Dim matches = regex.Matches(theText)

' The first capture group contains the matched string without the second space.
Dim lines = (From m In matches Select m.Groups(1).Value).ToList()

Here is a screenshot of the program executing in LINQPad 4, showing the output is two words in each string, as required: screenshot

Upvotes: 0

Related Questions