C# Replace string by position [closed]

2019-09-14 03:23发布

I am trying to replace a comma in a string.

For example, the data is the currency value of a part.

Eg. 453,27 This is the value I get from an SAP database

I need to replace the comma to a period to fix the value to the correct amount. Now sometimes, it will be in the thousands.

Eg. 2,356,34 This value needs to be 2,356.34

So, I need help manipulating the string to replace comma that is 2 characters from the end.

Thanks for the help

6条回答
走好不送
2楼-- · 2019-09-14 03:58

A quick google search gave me this:

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

So your "charToUse" should be '.'. If it always is 2 characters from end, your index should be text.length - 3.

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

查看更多
等我变得足够好
3楼-- · 2019-09-14 04:06
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楼-- · 2019-09-14 04:10
string x = "2,356,34";
if (x[x.Length - 3] == ',')
{
    x = x.Remove(x.Length - 3, 1);
    x = x.Insert(x.Length - 2, ".");
}
查看更多
何必那么认真
5楼-- · 2019-09-14 04:21

Use this :

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;
查看更多
Root(大扎)
6楼-- · 2019-09-14 04:22
string a = "2,356,34";
int pos = a.LastIndexOf(',');
string b = a.Substring(0, pos) + "." + a.Substring(pos+1);

You'll need to add a bit of checking for cases where there are no commas in the string, etc. but that's the core code.

You could also do it with a regex, but this is simple and reasonably efficient.

查看更多
Lonely孤独者°
7楼-- · 2019-09-14 04:23

If I understand correctly, you always need to replace the last comma with a period.

public string FixSAPNumber(string number)
{
    var str = new StringBuilder(number);
    str[number.LastIndexOf(',')] = '.';
    return str.ToString();
}
查看更多
登录 后发表回答