How to remove escape sequences from stream

前端 未结 5 1405
后悔当初
后悔当初 2021-01-14 15:48

is there an quick way to find(and remove) all escape sequences from a Stream/String??

5条回答
  •  清酒与你
    2021-01-14 16:11

    You can use System.Char.IsControl() to detect control characters.

    To filter control characters from a string:

    public string RemoveControlCharacters(string input)
    {
        return
            input.Where(character => !char.IsControl(character))
            .Aggregate(new StringBuilder(), (builder, character) => builder.Append(character))
            .ToString();
    }
    

    To filter control characters from a stream you can do something similar, however you will first need a way to convert a Stream to an IEnumerable.

    public IEnumerable _ReadCharacters(Stream input)
    {
        using(var reader = new StreamReader(input))
        {
            while(!reader.EndOfStream)
            {
                foreach(var character in reader.ReadLine())
                {
                    yield return character;
                }
            }
        }
    }
    

    Then you can use this method to filter control characters:

    public string RemoveControlCharacters(Stream input)
    {
        return
            _ReadCharacters(input)
            .Where( character => !Char.IsControl(character))
            .Aggregate( new StringBuilder(), ( builder, character ) => builder.Append( character ) )
            .ToString();
    }
    

提交回复
热议问题