プログラミングとかブログ

Unity/C#/SRPGStudio/RPGツクールMVの情報とかその他気になったことを調べて書きます。

【C#】行頭にスペースを突っ込むプログラム

行頭が「(かぎかっこ)以外の場合、行頭に全角スペースを挿入します。
小説書くときにいちいちスペース打つのが面倒なので作りました。

・使い方
txtファイルをD&Dすると、スペース挿入後のtxtファイルをデスクトップに吐きます。

ダウンロード

・実行例
f:id:shirakamisauto:20160901084008p:plain
実行後
f:id:shirakamisauto:20160901084018p:plain

・コード

using System;
using System.Linq;
using System.IO;
using System.Text;

namespace SpaceInserter
{
    class Program
    {
        static void Main(string[] args)
        {            
            string path = "";
            if (args.Count() > 0)
                path = args[0];
            var c = new Inserter();
            var txt = c.Insert(path);
            var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            path = desktopPath + "\\" + path.Split('\\').Last().Insert(0, "new_");
            File.WriteAllText(path, txt);
        }
    }

    public class Inserter
    {
        public string Insert(string path)
        {
            string insertedText = "";
            using (var sr = new StreamReader(path, Encoding.GetEncoding("shift_jis")))
            {
                while (sr.Peek() >= 0)
                {
                    var txt = sr.ReadLine();
                    if (!string.IsNullOrEmpty(txt) && txt[0] != '「')
                        txt = txt.Insert(0, " ");
                    insertedText += txt + Environment.NewLine;
                }
            }
            return insertedText;
        }
    }
}