Pergunta

I need to reverse a word in my text box to display in a label and then have every other character in the string be replaced by a "-". for example: input is textbox1.text = worms. I need the output to be label1.text = s-r-w (which is "worms" reversed: "smrow" with the "o" and the "m" replaced with "-")

This is what I have so far

    Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As   System.EventArgs) Handles btnCalc.Click

    'Displays equipment in label in reverse order
    label1.Text = reverse(textbox1.Text)

    Function reverse(ByVal info As String) As String
    Dim intM As Integer, strTemp As String = ""
    intM = info.Length
    For intJ As Integer = intM - 1 To 0 Step -1
        strTemp &= info.Substring(intJ, 1)
    Next
    Return strTemp
End Function

I got the reverse part but I cant figure out where to start to replace every other character with "-". Sorry I didn't post this the first time. I am new to SO!

Thanks guys

Foi útil?

Solução

You can use Enumerable.Reverse and String.Replace:

Dim reversed = textBox1.text.Reverse()
label1.Text = New String(reversed.ToArray()).Replace("o", "-").Replace("m", "-")

or this little query which includes both:

Dim newChars = From c In textBox1.Text.Reverse()
               Select If({"o", "m"}.Contains(c), "-"c, c)
label1.Text = New String(newChars.ToArray())

or probably even better since it also handles surrogates using the "forgotten" VisualBasic StrReverse:

label1.Text = Strings.StrReverse(textBox1.Text).Replace("o", "-").Replace("m", "-")

Reversing a String that Contains Unicode Characters Expressed as Surrogate Pairs

Update if you need to replace every second character instead.

Dim newChars = textBox1.Text.Reverse().
    Select(Function(c, Index) If(Index Mod 2 = 0, c, "-"c) )
Label1.Text = New String(newChars.ToArray())

Finally here's an approach using a StringBuilder which replaces every nth character with another character if it's not an "ignore-character" (space in this case):

Public Shared Function ReplaceEveryNthChar(input As String, nth As Int32, newChar As Char, Optional ignoreChars As Char() = Nothing) As String
    If input Is Nothing Then
        Throw New ArgumentNullException("input")
    End If
    If input.Length = 0 Then Return ""
    If input.Length = 1 Then Return input ' don't replace the first as desired

    Dim ignore = New HashSet(Of Char)(If(ignoreChars, Enumerable.Empty(Of Char)()))
    Dim sb = New System.Text.StringBuilder(input.Length)
    Dim ignoredChars = 0 
    sb.Append(input(0)) ' don't replace the first as desired
    For pos As Int32 = 2 To input.Length
        Dim c = input(pos - 1) ' index zero based 
        If ignore.Contains(c) Then
            ignoredChars += 1
            sb.Append(c)
        ElseIf (pos - ignoredChars) Mod nth = 0 Then
            sb.Append(newChar)
        Else
            sb.Append(c)
        End If
    Next
    Return sb.ToString()
End Function

You use it in this way:

Dim chars = textBox1.Text.ToCharArray()
Array.Reverse(chars)
label1.Text = ReplaceEveryNthChar(New String(chars), 2, "-"c, {" "})

Outras dicas

An old school solution, using a string builder and reverse loop:

Private Function MagicReplace(str As String) As String
  Dim sb As New System.Text.StringBuilder
  For i = str.Length - 1 To 0 Step -1
    If i Mod 2 = 0 Then
      sb.Append(str.Chars(i))
    Else
      sb.Append("-")
    End If
  Next
  Return sb.ToString
End Function

Usage:

Dim output As String = MagicReplace("worms")
Console.WriteLine(output) 'outputs s-r-w
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top