C# 按位置替换字符串
本文关键字:字符串 替换 位置 | 更新日期: 2023-09-27 18:37:14
>我正在尝试替换字符串中的逗号。
例如,数据是部件的货币值。
例如 453,27 这是我从 SAP 数据库获得的值
我需要将逗号替换为句点以将值固定为正确的金额。现在有时,它会有数千个。
例如 2,356,34 此值需要为 2,356.34
因此,我需要帮助操作字符串以替换末尾 2 个字符的逗号。
感谢您的帮助
string a = "2,356,34";
int pos = a.LastIndexOf(',');
string b = a.Substring(0, pos) + "." + a.Substring(pos+1);
您需要添加一些检查字符串中没有逗号等的情况,但这是核心代码。
您也可以使用正则表达式来做到这一点,但这既简单又合理高效。
快速的谷歌搜索给了我这个:
void replaceCharWithChar(ref string text, int index, char charToUse)
{
char[] tmpBuffer = text.ToCharArray();
buffer[index] = charToUse;
text = new string(tmpBuffer);
}
所以你的"字符使用"应该是"."。如果它始终从末尾开始 2 个字符,则索引应为文本长度 - 3.
http://www.dreamincode.net/code/snippet1843.htm
如果我理解正确,您总是需要用句点替换最后一个逗号。
public string FixSAPNumber(string number)
{
var str = new StringBuilder(number);
str[number.LastIndexOf(',')] = '.';
return str.ToString();
}
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)
使用这个:
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;
string x = "2,356,34";
if (x[x.Length - 3] == ',')
{
x = x.Remove(x.Length - 3, 1);
x = x.Insert(x.Length - 2, ".");
}