ソース整形2
- 目的:
ソースコードのインデントを変更し、見やすくする。
- 実現方法:
ソースファイルのデータを一行ずつ取得し、
中かっこの有無でインデントを進めるか判断するようにした。
- 成果物:
using System; using System.IO; using System.Linq; using EnvDTE; //Add Reference to EnvDTE,EnvDTE80 using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { string data = ""; StringBuilder result = new StringBuilder(); List<string> indexIncreaseData = new List<string> { "{", "if" }; List<string> indexDecreaseData = new List<string> { "}"}; int indentCount = 0; StreamReader sr = new StreamReader(@"C:\test\src.txt"); while (!sr.EndOfStream) { data = sr.ReadLine(); // 先頭の空白を除去 data = Regex.Replace(data, "^ +", ""); if (data.Split(new char[] { ' ' }).Where(n => indexDecreaseData.Contains(n)).Count() == 0) { data = new String(' ', (indentCount * 4)) + data; } if (data.Split(new char[] { ' ' }).Where(n => indexIncreaseData.Contains(n)).Count() > 0) { // indent proceed indentCount++; } if (data.Split(new char[] { ' ' }).Where(n => indexDecreaseData.Contains(n)).Count() > 0) { // indent back data = new String(' ', (--indentCount * 4)) + data; } result.AppendLine(data); } StreamWriter sw = new StreamWriter(@"C:\test\src1.cs"); sw.Write(result.ToString()); sw.Close(); } } }
- ナレッジ:
- using EnvDTE; //Add Reference to EnvDTE,EnvDTE80
DTE:"Development Tools Extensibility" の略語
→Visual Studioコアオートメーションのオブジェクトとメンバを含むアセンブリラップCOMライブラリです。
→Visual Studioからアクティブなウインドウやアプリケーションを制御可能。
- COM:Component Object Modelの略語
→特定のプログラミングに依存せず利用できる、バイナリコード単位のインターフェース。
- List
indexIncreaseData = new List { "{", "if" };
Listの初期化でいつも間違える。new List
- 同じ文字列を指定回数繰り返した文字の作成方法
一文字の場合:new String('a', 10)
複数文字の場合:(new string('a', 10)).Replace("a", "hoge");
- お世話になったサイト:
- DTEの意味
ttps://stackoverflow.com/questions/17239760/what-is-the-visual-studio-dte
ttps://docs.microsoft.com/en-us/dotnet/api/envdte.document?view=visualstudiosdk-2017
- 正規表現による置換
ttps://dobon.net/vb/dotnet/string/replace.html
- 同じ文字列を指定回数繰り返した文字の作成方法