从txt读取后的C#字符串拆分

时间:2017-10-29 11:02:19

标签: c# string split streamreader

所以我有一个非常庞大的带有单词和字符的txt文件。 例如:

Hello! How Are You ?

当我使用streamreader时,我想将它拆分为:

{
  "services": [
    {
        "_id": "59f58f2c43f4aa7f7ec4ce4d",
        "name": "appName",
        "type": "app"
    },
    {
        "_id": "59f5b34e218e567f840bc592", 
        "name": "appName2", 
        "type": "app"
    }
  ]
}

所以当"返回"出现在文本中,在行中打破。 当它说" Space"用空炭替换它#34; &#34 ;. 如果有" KeyOemcomma"将其替换为"?"。

我怎么能这样做?我尝试了很多选择,但它对我没用..:/

4 个答案:

答案 0 :(得分:2)

使用StringBuilder替换功能。它比string替换要快得多。

string a = "Hello!ReturnHowspaceyouspacearespacedoing?";
            StringBuilder sb = new StringBuilder(a);
            sb.Replace("Return", Environment.NewLine).Replace("space", " ");

            Console.WriteLine(sb.ToString());

查看here了解详情。

答案 1 :(得分:0)

以下是可以执行此操作的简单代码块:

string input = "Hello!ReturnHowSpaceAreSpaceYouKeyOemcomma";            
var textAfterReplacingReturn = input.Replace("Return", "\n");
var textAfterReplacingSpace = textAfterReplacingReturn.Replace("Space", " ");
var finalText = textAfterReplacingSpace.Replace("KeyOemcomma", "?");
Console.WriteLine(finalText);

当然,您可以在一行中进行更换:

string input = "Hello!ReturnHowSpaceAreSpaceYouKeyOemcomma";            
var resultString = input.Replace("Return", "\n").Replace("Space", " ").Replace("KeyOemcomma", "?");
Console.WriteLine(resultString);

答案 2 :(得分:0)

我的解决方案two streams

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

class Transformer {
    readonly StreamReader _input;
    readonly Dictionary<string, char> _str2Char;

    public Transformer(Stream stream, Dictionary<string, char> str2Char) {
        _input = new StreamReader(stream);
        _str2Char = str2Char;

    }
    public Stream Transfrom() {
        var output = new StreamWriter(new MemoryStream());

        int c = -1;
        // Buffer to keep read chars
        var buffer = new StringBuilder();
        // Read until the end of stream (-1)
        while ((c = _input.Read()) != -1) {
            char ch = (char)c;
            // We separate input stream by upper char
            if (char.IsUpper(ch)) {
                if (buffer.Length >= 2) {
                    var str = buffer.ToString();
                    // We have to process "KeyOemcomma" individually
                    bool isSpecialCase = str == "Key" && ch == 'O';
                    if (!isSpecialCase) {
                        WriteToOutput(str, output);
                        buffer.Clear();
                    }
                    // Here should be more logic, if it was not "KeyOemcomma"
                    buffer.Append(ch);
                }
                else buffer.Append(ch);
            }
            else buffer.Append(ch);
        }
        if (buffer.Length > 0) {
            WriteToOutput(buffer.ToString(), output);
            buffer.Clear();
        }
        output.Flush();
        return output.BaseStream;
    }

    void WriteToOutput(string str, StreamWriter output) {
        // Console.WriteLine(str);
        char c;
        if (_str2Char.TryGetValue(str, out c))
            output.Write(c);
        else 
            output.Write(str);
    }
}

public class Program
{
    public static void Main()
    {
        Dictionary<string, char> str2Char = new Dictionary<string, char> {
            {"Return", '\n'},
            {"Space", ' '},
            {"KeyOemcomma", '?'}
        };
        string str = "Hello!ReturnHowSpaceAreSpaceYouKeyOemcomma";
        var input = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str));
        var t = new Transformer(input, str2Char);
        var output = t.Transfrom();

        // Start reading output stream from the begining
        output.Seek(0, SeekOrigin.Begin);
        var s = new StreamReader(output);

        int c;
        while ((c = s.Read()) != -1) {
            Console.Write((char)c);
        }
    }
}

答案 3 :(得分:0)

如果这些是您想要的唯一替代品,我会选择kakroo的回答 但是,如果您需要替换更长的列表,我可能会这样做:

string input = "Hello!ReturnHowSpaceAreSpaceYouKeyOemcomma";

var replacements = new List<Tuple<string,string>>()
{
    Tuple.Create("Return", "\n"),
    Tuple.Create("Space", " "),
    Tuple.Create("KeyOemcomma", "?") //, add whatever other replacements here...
};
var sb = new StringBuilder(input);
foreach(var replacement in replacements)
{
    sb.Replace(replacement.Item1, replacement.Item2);
}
string result = sb.ToString();

You can see a live demo on rextester.