user8851296
user8851296

Reputation:

C# String splitting after reading it from txt

So I have a very huge txt file with words and characters. For example:

Hello!ReturnHowSpaceAreSpaceYouKeyOemcomma

When I use the streamreader I would like to split it like this:

Hello!
How Are You ?

So when "Return" appears in text, do a break in lines. When it says "Space" replace it with an empty char " ". If there's "KeyOemcomma" replace it to "?".

How could I do this? I've tried many options but it didn't work for me..:/

Upvotes: 1

Views: 221

Answers (4)

Zohar Peled
Zohar Peled

Reputation: 82474

If these are the only replacements you want, I would go with kakroo's answer.
However, if you have a longer list of stuff you need to replace, I would probably do it like this:

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.

Upvotes: 0

Artavazd Balayan
Artavazd Balayan

Reputation: 2413

My solution with 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);
        }
    }
}

Upvotes: 0

kkakroo
kkakroo

Reputation: 1113

Use StringBuilderreplace function. It's much faster than string replace.

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

            Console.WriteLine(sb.ToString());

Check here for more info.

Upvotes: 4

Merdigon
Merdigon

Reputation: 5

Here is simple block of code that can do this:

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

Of course, you can do replacing in one line:

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

Upvotes: 0

Related Questions