gpt4 book ai didi

C#用多个逗号替换字符串中的两个特定逗号

转载 作者:太空宇宙 更新时间:2023-11-03 21:54:52 25 4
gpt4 key购买 nike

我正在尝试将每行中的日期格式从逗号更改为连字符。分隔月日日年的逗号索引不同。

   lines_in_List[i] = lines_in_List[i].Insert(0, cnt + ","); // Insert Draw # in 1st column

string one_line = lines_in_List[i];
// 0,5,1,2012,1,10,19,16,6,36,,,
// 1,11,5,2012,49,35,23,37,38,28,,,
// 2,12,10,2012,8,52,53,54,47,15,,,
// ^-^--^ replace the ',' with a '-'.

StringBuilder changed = new StringBuilder(one_line);
changed[3] = '-';
changed[5] = '-';
changed[3] = '-';
lines_in_List[i] = changed.ToString();
}

最佳答案

您可以使用采用初始偏移量的 IndexOf 重载来开始搜索。

http://msdn.microsoft.com/en-us/library/5xkyx09y.aspx

int idxFirstComma = line.IndexOf(',');
int idxSecondComma = line.IndexOf(',', idxFirstComma+1);
int idxThirdComma = line.IndexOf(',', idxSecondComma+1);

使用这些索引进行替换。

要有效地替换这些字符(无需创建大量临时字符串实例),请查看:

http://www.dotnetperls.com/change-characters-string

该片段将字符串转换为字符数组,进行替换,然后创建一个新字符串。

关于C#用多个逗号替换字符串中的两个特定逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12736380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com