简体   繁体   English

C#替换字符串中的某种字符

[英]C# replace a certain type of character in a string

Let's say I've got a string with the value of "C4". 假设我有一个值为“ C4”的字符串。 In my code I generate some number, let's say it's 200, and now I want my string to look like this: "C200". 在我的代码中,我生成一些数字,假设它是200,现在我希望我的字符串看起来像这样:“ C200”。 Of course that nothing is known at compile time. 当然,在编译时一无所知。

Is it possible to do this change with a single elegant line? 可以用一条优雅的线条进行此更改吗? I know this line I will write is not syntactically correct but this is the idea I'm looking for: 我知道我要写的这一行在语法上不正确,但这就是我要寻找的主意:

newString = oldString.Replace(typeof (int), newNumber.ToString());

您可以使用正则表达式:

newString = Regex.Replace(oldString, @"\d+", newNumber.ToString());

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

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