如何用 "dash" 或 "symbol" 替换字符串中单词的偶数字符?

How to replace even character of words in a string with "dash" or "symbol"?

我正在尝试从字符串中提取单词,然后用破折号替换偶数字符..(不包括白色 space)来为文字游戏提供一种提示。例如:

InputString="English Language"

OutputString = "#n#l#s# #a#g#a#e"

目前,我使用以下代码:

Private Sub Hint()

    Dim InputString as string = "English Language"
    dim SubInput as string()
    SubInput=InputString.Split(" ")

    For i=0 to UBound(SubInput) 'run through all items in SubInput array

        For k=0 to SubInput(i).length-1 'run through all characters in one item 

        If k mod 2= 0 then 'Do the replacement if even characters found
                SubInput(i)=SubInput(i).Replace(SubInput(i).Chars(k),"#") 
        End If

        Next

    Next

    Dim OutputString=String.Join(" ",subInput(i))
    Msgbox(OutputString)

    End Sub

但是,我收到的消息框显示“

#n#l#s# #a###a#e

” 单词:Language 被错误替换为第 (3)

号字符

你能指出如何修复它吗?

非常感谢~

如下所示尝试 linq,

   string s = "English Language";
   string[] split = s.Split(" ");
   for(int j=0;j<split.length;j++)
   {
    var outStr = string.Concat(split[j].Select((c,i) => i%2==0 ? "#" : c.ToString()));
    split[j]= outStr;
   }
   s= String.Join(" ",split);

代码在 C# 中,但您可以使用转换器将其转换为 vb.net

你能试试这个吗code.much 易于实施和理解

Dim s As String = "English Language"
        Dim intcount As Integer = 0
        For Each c As Char In s
            If intcount Mod 2 = 0 and c <> "" Then
                s = s.Remove(intcount, 1).Insert(intcount, "#")
            End If
            intcount += 1
        Next
 Return s

希望这对您有所帮助。

(?<=^(?:\S\S|\s\S|\S\s)*).

您可以使用它并替换为 #See Demo

按照正则表达式会很多better.You可以在一行代码中实现输出。

 Dim InputString As String = "English Language"
 OutputString = System.Text.RegularExpressions.Regex.Replace(InputString, "(?<=^(?:\S\S|\s\S|\S\s)*).", "#")

(?<=^(?:\S\S|\s\S|\S\s)*). - 是要过滤的模式(在输入字符串的偶数索引中查找字符)您的输入字符串将替换为 #

Live Demo


msdn,tutorialspoint

学习 vb.net 的正则表达式