Skip to content

Convert to interpolated strings #45438

@gewarren

Description

@gewarren

Use this console app generated by GitHub Copilot to convert to interpolated strings:

using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string directory = "c:\\repos\\docs\\docs\\fundamentals\\runtime-libraries";
        if (!Directory.Exists(directory))
        {
            Console.WriteLine($"Directory '{directory}' does not exist.");
            return;
        }

        foreach (string file in Directory.GetFiles(directory, "*.cs", SearchOption.AllDirectories))
        {
            ConvertFileToInterpolatedStrings(file);
        }
    }

    static void ConvertFileToInterpolatedStrings(string filePath)
    {
        string fileContent = File.ReadAllText(filePath);
        string updatedContent = ConvertToInterpolatedStrings(fileContent);

        if (fileContent != updatedContent)
        {
            File.WriteAllText(filePath, updatedContent);
            Console.WriteLine($"Updated file: {filePath}");
        }
    }

    static string ConvertToInterpolatedStrings(string content)
    {
        string pattern = @"Console\.WriteLine\(([^;]*)\);";
        return Regex.Replace(content, pattern, match =>
        {
            string arguments = match.Groups[1].Value;
            string[] parts = SplitArgument(arguments);

            if (parts.Length < 2)
                return match.Value;

            string formatString = parts[0].Trim();
            string[] formatArguments = parts[1..].Select(arg => arg.Trim()).ToArray();

            if (!formatString.StartsWith('"') || !formatString.EndsWith('"'))
                return match.Value;

            formatString = formatString[1..^1]; // Remove quotes

            string interpolatedString = "Console.WriteLine($\"" + Regex.Replace(formatString, @"\{(\d+)(,[^}]*)?(:[^}]*)?\}", m =>
            {
                int index = int.Parse(m.Groups[1].Value);
                string alignment = m.Groups[2].Value;
                string formatSpecifier = m.Groups[3].Value;

                if (index < formatArguments.Length)
                {
                    return "{" + formatArguments[index].Trim() + alignment + formatSpecifier + "}";
                }
                return m.Value;
            }) + "\");";

            return interpolatedString;
        });
    }

    static string[] SplitArgument(string argument)
    {
       var parts = new List<string>();
        int bracketCount = 0;
        int start = 0;

        for (int i = 0; i < argument.Length; i++)
        {
            if (argument[i] == ',' && bracketCount == 0)
            {
                parts.Add(argument[start..i].Trim());
                start = i + 1;
            }
            else if (argument[i] == '(')
            {
                bracketCount++;
            }
            else if (argument[i] == ')')
            {
                bracketCount--;
            }
        }

        parts.Add(argument[start..].Trim());
        return [.. parts];
    }
}

Metadata

Metadata

Assignees

Labels

in-prThis issue will be closed (fixed) by an active pull request.resolved-by-customer

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions