简体   繁体   English

C#替换字符串中字符选择的每个实例

[英]c# replace each instance of a character selection in a string

I've found many references to do similar to this but none seem to be exactly what I'm after, so hoping someone could help. 我发现有很多类似的参考文献,但似乎都不是我想要的,因此希望有人能提供帮助。
In simple terms, I want to take a string entered by a user (into a Winform input), and firstly strip out any blanks, then replace any of a list of 'illegal' characters with the UK currency symbol (£). 简单来说,我想将用户输入的字符串(输入到Winform输入中),首先去除所有空格,然后用英国货币符号(£)替换任何“非法”字符列表。 The requirement is for the input to be used but the file that is generated by the process has the modified filename. 要求使用输入,但该流程生成的文件具有修改后的文件名。
I wrote a function (based on an extension method) but it's not working quite as expected: 我写了一个函数(基于扩展方法),但没有按预期工作:

public static class ExtensionMethods
    {
        public static string Replace(this string s, char[] separators, string newVal)
        {
            var temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            return String.Join(newVal, temp);
        }
    }

public static string RemoveUnwantedChars(string enteredName, char[] unwanted, string rChar)
    {
        return enteredName.Replace(unwanted, rChar);
    }

Which in my code, I've called twice: 在我的代码中,我已经两次调用:

char[] blank = { ' ' };
string ename = Utilities.RemoveUnwantedChars(this.txtTableName.Text, blank, string.Empty);

char[] unwanted = { '(', ')', '.', '%', '/', '&', '+' };
string fname = Utilities.RemoveUnwantedChars(ename, unwanted, "£");

If I enter a string that contains at least one space, all of the characters above and some other letters (for example, " (GH) F16.5% MX/Y&1+1"), I get the following results: 如果我输入的字符串至少包含一个空格,上面的所有字符以及其他一些字母(例如,“(GH)F16.5%MX / Y&1 + 1”),则会得到以下结果:
ename = "(GH)F16.5%MX/Y&1+1" - this is correct in that it has removed the blanks. ename =“(GH)F16.5%MX / Y&1 + 1”-这是正确的,因为它已删除了空格。
fname = "GH£F16£5£MX£Y£1£1" - this hasn't worked correctly in that it has not replaced the first character but removed it. fname =“ GH£F16£5£MX£Y£1£1”-这不能正常工作,因为它没有替换第一个字符而是将其删除。
The rest of the characters have been correctly replaced. 其余字符已正确替换。 It only occurs when one of the 'illegal' characters is at the start of the string - if my string was "G(H) F16.5% MX/Y&1+1", I would correctly get "G£H£F16£5£MX£Y£1£1". 仅当字符串中的“非法”字符之一位于字符串开头时,如果我的字符串是“ G(H)F16.5%MX / Y&1 + 1”,我会正确获得“ G£H£F16£ 5£MX£Y£1£1”。 It also replaces multiple 'illegal' characters with one '£', so "M()GX+.1" would become "M£GX£1" but should be "M££GX££1". 它还用一个“£”替换多个“非法”字符,因此“ M()GX + .1”将变成“ M£GX£1”,但应为“ M££GX£1”。

I think the problem is in your Replace extension. 我认为问题出在您的替换扩展名中。 You are splitting in this line 您在这一行中分裂

var temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);

You are removing empty entries causing the unexpected result. 您正在删除导致意外结果的空条目。 Use this instead: 使用此代替:

var temp = s.Split(separators, StringSplitOptions.None);

The problem is occuring because string.Join() only puts separators between substrings - it will never put one at the start. 之所以出现此问题,是因为string.Join()子字符串之间放置分隔符-绝不会在开始处放置一个分隔符。

One possible solution is to avoid using string.Join() and write Replace() like this instead: 一种可能的解决方案是避免使用string.Join()并改为这样编写Replace()

public static class ExtensionMethods
{
    public static string Replace(this string s, char[] separators, string newVal)
    {
        var sb = new StringBuilder(s);

        foreach (char ch in separators)
        {
            string target = new string(ch, 1);
            sb.Replace(target, newVal);
        }

        return sb.ToString();
    }
}

When you use split method in your Replace function you get following strings: GH, F16, 5, MX, Y, 1, 1. When you join them with your newVal you get: GH + newVal + F16 + newVal + ... thus omitting first replaced character. 当您在Replace函数中使用split方法时,您将获得以下字符串:GH,F16、5,MX,Y,1、1。将它们与newVal结合使用时,您将得到:GH + newVal + F16 + newVal + ...因此省略第一个替换的字符。

You would probably need some special case to check if first char is "illegal" and put newVal at start of your string. 您可能需要一些特殊情况来检查第一个字符是否为“非法”,并将newVal放在字符串的开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM