VB.NET用一行代码替换字符串中的多个字符 [英] Replace multiple characters in string in one line of code in VB.NET

查看:141
本文介绍了VB.NET用一行代码替换字符串中的多个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 VB.NET 我希望能够在一行代码中替换字符串中的一系列字符.

Using VB.NET I'd like to be able to replace a range of characters in a string in a single line of code.

即,类似于:

Dim charsToReplace as string = "acegi"
Dim stringToBeReplaced as string = "abcdefghijklmnop"

charsToReplace.ToArray().ForEach(Function (c) stringTobeReplaced = stringTobeReplaced.Replace(c, ""))

然而,这不起作用.

以下确实有效,但是我不希望字符串成为类级别变量:

The following does work, however I don't want the string to be a class level variable:

 Sub Main()
    Dim toReplace As String = "acegikmoq"

    Console.WriteLine(mainString)
    Dim chars As List(Of Char) = toReplace.ToList()
    chars.ForEach(AddressOf replaceVal)

    Console.WriteLine(mainString)
    Console.ReadLine()
End Sub

Dim mainString As String = "this is my string that has values in it that I am going to quickly replace all of..."

Sub replaceVal(ByVal c As Char)
    mainString = mainString.Replace(c, "")
End Sub

这能做到吗?

推荐答案

如果我没看错,您是在尝试从字符串中去除字符列表.这非常适合 RegEx.

If I read this correctly, you're trying to strip a list of characters from a string. This is a good fit for a RegEx.

Console.WriteLine(Regex.Replace("abcdefghijklmnop", "[acegi]", string.Empty))

(你需要导入 System.Text.RegularExpressions)

(you'll need to import System.Text.RegularExpressions)

这篇关于VB.NET用一行代码替换字符串中的多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆