c# 判断是否由string.Format生成 包含{0}的字符串

using System;
using System.Linq;

public class Program
{
    public static bool IsStringFormatBuild(string befStr, string aftStr)
    {
        try
        {
            string[] placeholders = { "{0}", "{1}", "{2}", "{3}" };

            var newStr = befStr;

            foreach (var placeholder in placeholders)
            {
                newStr = newStr.Replace(placeholder, "&&&");
            }

            var parts = newStr.Split(new[] { "&&&" }, StringSplitOptions.None);

            return parts.All(part => aftStr.Contains(part));
        }
        catch
        {
            return false;
        }
    }

    public static void Main()
    {
        string befStr = "{0} is a {1} example with {2} placeholders.";
        string aftStr = "This is a simple example with some placeholders.";

        bool result = IsStringFormatBuild(befStr, aftStr);

        Console.WriteLine(result); // Output: True
    }
}

你可能感兴趣的:(c#)