【问题标题】:C# Replace string by position [closed]C#按位置替换字符串[关闭]
【发布时间】:2012-06-18 12:49:44
【问题描述】:

我正在尝试替换字符串中的逗号。

例如,数据是零件的货币价值。

例如。 453,27 这是我从 SAP 数据库得到的值

我需要将逗号替换为句点以将值固定为正确的数量。现在有时,它会成千上万。

例如。 2,356,34 这个值需要是2,356.34

所以,我需要帮助来处理字符串以替换最后 2 个字符的逗号。

感谢您的帮助

【问题讨论】:

  • 如果逗号是千位分隔符或小数分隔符,为什么要以这种方式存储像 2,356,34 这样的数字?这对我来说看起来很奇怪
  • 你也应该向我们展示你已经尝试过的东西
  • 这只是它来自数据库的方式。数据库像这样保存它,并且它以某种方式理解它。这对我来说也没有意义。

标签: c# string replace


【解决方案1】:

使用这个:

string str = "2,356,34";
string[] newStr = str.Split(',');
str = string.Empty;
for (int i = 0; i <= newStr.Length-1; i++)
{
    if (i == newStr.Length-1)
    {
        str += "."+newStr[i].ToString();
    }
    else if (i == 0)
    {
        str += newStr[i].ToString();
    }
    else
    {
        str += "," + newStr[i].ToString();
    }
}
string s = str;

【讨论】:

    【解决方案2】:
    string x = "2,356,34";
    if (x[x.Length - 3] == ',')
    {
        x = x.Remove(x.Length - 3, 1);
        x = x.Insert(x.Length - 2, ".");
    }
    

    【讨论】:

    • 意识到千位数字也使用句点作为逗号。使用您的代码将这两个问题更改为正确的格式。
    • @tluck234 - 这更有意义。您收到 European 格式,正在尝试读取其值,但您的解析设置为 American 文化。另一种解决方法是在您解析它时将文化设置为欧洲。 [我不知道确切的细节,但请查看“文化”/“千位分隔符”/“小数点”]。
    【解决方案3】:
    string item_to_replace = "234,45";
    
    var item = decimal.Parse(item_to_replace);
    
    var new_item = item/100;
    
    //if you need new_item as string 
    //then new_item.ToString(Format)
    

    【讨论】:

      【解决方案4】:

      如果我理解正确,您总是需要用句点替换最后一个逗号。

      public string FixSAPNumber(string number)
      {
          var str = new StringBuilder(number);
          str[number.LastIndexOf(',')] = '.';
          return str.ToString();
      }
      

      【讨论】:

        【解决方案5】:

        快速的谷歌搜索给了我这个:

        void replaceCharWithChar(ref string text, int index, char charToUse)
        {
            char[] tmpBuffer = text.ToCharArray();
            buffer[index] = charToUse;
            text = new string(tmpBuffer);
        }
        

        所以你的“charToUse”应该是'.'。如果它总是距离结尾 2 个字符,那么您的索引应该是 text.length - 3。

        http://www.dreamincode.net/code/snippet1843.htm

        【讨论】:

        • 应该是-3而不是-2。 :)
        • 糟糕,同时在打电话:)
        【解决方案6】:
        string a = "2,356,34";
        int pos = a.LastIndexOf(',');
        string b = a.Substring(0, pos) + "." + a.Substring(pos+1);
        

        您需要添加一些检查字符串中没有逗号的情况等,但这是核心代码。

        您也可以使用正则表达式来完成,但这既简单又相当有效。

        【讨论】:

        • 把这个放进去。像梦一样跑。添加到数据库时不再出现错误。 LastIndex 是它的关键。我曾尝试过类似的方法,但无法弄清楚如何将其置于该位置。非常感谢。将很快标记为答案
        • 这个效率很低
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-24
        • 1970-01-01
        • 2014-07-13
        • 2011-06-28
        • 2013-03-08
        相关资源
        最近更新 更多