简体   繁体   English

如何在 C# 中将 char 替换两次?

[英]How to replace char two times in C#?

I have a string "%hello%" and i want to get output "{hello}" .我有一个字符串"%hello%" ,我想得到 output "{hello}" I tried all my ideas but not working or not compiling.我尝试了所有想法,但没有工作或没有编译。 I added now compile error, i know the problem is in array index.我现在添加了编译错误,我知道问题出在数组索引中。 It's my code:这是我的代码:


char[] charArr = vars.xyz.ToCharArray();
StringBuilder asda = new StringBuilder(vars.xyz);
foreach (char ch in charArr)
{
    vars.count++;
    vars.charArrayCounter++;
    if (ch.Equals('%'))
    {
        vars.charCounter++;
    }
    switch (vars.charCounter)
    {
        case 1:
            asda[vars.charArrayCounter - 1] = '{';
            break;
        case 2:
            asda[vars.charArrayCounter - 1] = '{';
            vars.charCounter = 0;
            break;
    }
}

I get compile error:我得到编译错误:

System.ArgumentOutOfRangeException: „Index was out of range. System.ArgumentOutOfRangeException:“索引超出范围。 Must be non-negative and less than the size of the collection.必须是非负数且小于集合的大小。

In line: asda[vars.charArrayCounter - 1] = '{';在线: asda[vars.charArrayCounter - 1] = '{';

var asda = System.Text.RegularExpressions.Regex.Replace(vars.xyz, @"%([^%]+)%", "{$1}");

Your juggling with indexes is error prone, specially if you have those as global state.您处理索引很容易出错,特别是如果您有全局 state。

If I keep close to what you have now I suggest building up the StringBuilder by appending a char one by one and keep state to know if you encounteres a % character so you know what you need to append instead.如果我与您现在所拥有的保持接近,我建议通过逐个附加一个字符来构建 StringBuilder 并让 state 知道您是否遇到%字符,这样您就知道您需要 append 来代替。 That solves the Index out of range exeception by simply omitting index operations from the loop.这通过简单地从循环中省略索引操作来解决索引超出范围异常。

If I assume your vars is simlar to this:如果我假设您的vars与此类似:

static class vars
{
  public static string xyz ="%hello%"; 
}

That code could look like this:该代码可能如下所示:

char[] charArr = vars.xyz.ToCharArray();
StringBuilder asda = new StringBuilder();
var state = 0; // counter for 1st or 2nd replace
foreach (char ch in charArr)
{
    if (ch.Equals('%'))
    {
        switch(state)
        {
            case 0: // first
                asda.Append('{');     
            break;
            case 1: //second
                asda.Append('}');     
            break;
            default:
                // error? because we have now found 3 % chars
            break;
        }
        state++; // counter goes up
    } else {
      asda.Append(ch);  // add to the stringbuilder
    }
}

and that outputs {hello} in my testing.在我的测试中输出 {hello} 。 It will produce for %hel%lo% the result {hel}lo% but you can know something was off because state will be > 1.它将为 %hel%lo% 产生结果 {hel}lo% 但您可以知道有些东西已经关闭,因为 state 将 > 1。

The much shorter alternative (which opens new error cases) but omits any loops, leverages the IndexOf and LastIndexOf methods of the String class更短的替代方案(打开新的错误案例)但省略任何循环,利用 String class 的 IndexOf 和 LastIndexOf 方法

StringBuilder asda2 = new StringBuilder(vars.xyz);
asda2[vars.xyz.IndexOf('%')]='{';
asda2[vars.xyz.LastIndexOf('%')]='}';

This has the benfit it will for the input %hel%lo% the result {hel%lo} which is maybe preferble.这对输入 %hel%lo% 的结果 {hel%lo} 有好处,这可能是更可取的。 Do check if the input as a % at all, or it fail.请检查输入是否为 %,否则会失败。 I leave that for others to solve.我把它留给其他人解决。

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

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