c# - 如何在 C# 中转换具有 C 类型占位符(%d、%x 等)的字符串
问题描述
我需要将变量插入到 C 字符串类型的占位符中。我需要用 C# 来做。(我知道在 Java 中它适用于 String.format) 请注意,我不知道有多少变量,以及期望的类型。我得到了 originalString 字符串!无法将格式更改为 C# 约定。示例:
string originalString= "this is my number %d";
int myNumber = 3;
string result= string.Format(originalString, myNumber);//This doesn't work in C#!
解决方案
为了匹配然后替换%d
,%i
和类似的构造,你可以尝试正则表达式。最简单的(只是一个替代)代码可以是
using System.Text.RegularExpressions;
...
private static string MyFormat(string source, params object[] args) {
int index = 0;
return Regex.Replace(source, "%[isdf]", match => args[index++]?.ToString());
}
接着
string result = MyFormat(
"this is my number %d next number is %d and string is %s", 3, 5, "STR");
Console.Write(result);
结果:
this is my number 3 next number is 5 and string is STR
如果您不只是要替换%d
,%i
等等。但是实现一些详细的逻辑,你可以使用下面的代码:
private static string MyFormat(string source, params object[] args) {
int index = 0;
return Regex.Replace(source, "%[sdfx]", match => {
string pattern = match.Value.TrimStart('%'); // "s", "d", "x" and the like
object value = args[index++]; // 3, 5, STR etc
//TODO: apply special logic here and return the formatted value
return value.ToString();
});
}
推荐阅读
- web-scraping - 如何获取 youtube 视频 ID
- excel - Excel PDF 导出 - 在新选项卡中打开超链接
- asynchronous - 为什么在 main 函数完成后 Future 工作?
- git - 在 Github 上写完代码可以在线运行吗?
- python - 当只传递网络的输入和输出时,keras 功能 API 模型如何知道层
- python - 在 Django 中使用嵌套序列化程序创建 2 个相关模型的实例
- git - 从另一个分支创建的变基分支
- c# - Net core 3.1 mvc 应用程序部署为 Windows 服务
- java - Java Concurrent Hashmap initTable() 为什么 try/finally 阻塞?
- wordpress - 我的 WordPress 缩略图比原始缩略图大得多(以字节为单位)