我需要在文本框中反转一个单词以显示在标签中,然后将字符串中的每个其他字符替换为“ - ”。例如:输入为textbox1.text = worms
。我需要输出为label1.text = s-r-w
(“蠕虫”反转:“smrow”用“o”而“m”用“ - ”代替)
这是我到目前为止所拥有的
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
我得到了相反的部分,但我无法弄清楚从哪里开始用“ - ”替换所有其他角色。对不起,我没有第一次发布这个。我是SO的新手!
谢谢你们
答案 0 :(得分:2)
您可以使用Enumerable.Reverse
和String.Replace
:
Dim reversed = textBox1.text.Reverse()
label1.Text = New String(reversed.ToArray()).Replace("o", "-").Replace("m", "-")
或这个包含两者的小查询:
Dim newChars = From c In textBox1.Text.Reverse()
Select If({"o", "m"}.Contains(c), "-"c, c)
label1.Text = New String(newChars.ToArray())
或者甚至可能更好,因为它还使用"忘记"处理代理人。 VisualBasic StrReverse
:
label1.Text = Strings.StrReverse(textBox1.Text).Replace("o", "-").Replace("m", "-")
Reversing a String that Contains Unicode Characters Expressed as Surrogate Pairs
如果您需要替换每个第二个字符,请更新。
Dim newChars = textBox1.Text.Reverse().
Select(Function(c, Index) If(Index Mod 2 = 0, c, "-"c) )
Label1.Text = New String(newChars.ToArray())
最后这里是一种使用StringBuilder
的方法,如果它不是" ignore-character&#34,则将每个第n个字符替换为另一个字符; (在这种情况下的空间):
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
你以这种方式使用它:
Dim chars = textBox1.Text.ToCharArray()
Array.Reverse(chars)
label1.Text = ReplaceEveryNthChar(New String(chars), 2, "-"c, {" "})
答案 1 :(得分:0)
旧学校解决方案,使用字符串构建器和反向循环:
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
用法:
Dim output As String = MagicReplace("worms")
Console.WriteLine(output) 'outputs s-r-w