Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Text;
- using System.Collections.Generic;
- using System.IO;
- namespace TSV
- {
- public static class TSV
- {
- public static void ToString(TextWriter w, string[] inputs)
- {
- bool first = true;
- foreach(string col in inputs)
- {
- if( first )
- first = false;
- else
- w.Write( '\t' );
- if( col.Contains( "\"" ) || col.Contains( "\t" ) || col.Contains( "\n" ) || col.Contains( "\r" ) )
- w.Write(string.Format( "\"{0}\"", col.Replace( "\"", "\"\"" ) ));
- else
- w.Write( col );
- }
- }
- public static void FromString(TextReader r, out string[] ret)
- {
- List<string> list = new List<string>();
- StringBuilder sb = new StringBuilder();
- while( true )
- {
- int ic = r.Read();
- if( ic < 0 )
- break;
- char c = (char)ic;
- switch( c )
- {
- case '\t':
- list.Add( sb.ToString() );
- sb.Clear();
- break;
- case '\n': // reached end of this TSV
- break;
- case '"':
- // parse
- while( true )
- {
- ic = r.Read();
- if( ic < 0 )
- break;
- c = (char)ic;
- if( c == '"' )
- {
- if( r.Peek() == '"' ) // is it escaped?
- {
- r.Read(); // read the 2nd quote
- sb.Append( '"' );
- }
- else
- break; // reached the end of the quote
- }
- else
- sb.Append( c );
- }
- break;
- default:
- sb.Append( c );
- break;
- }
- }
- if(sb.Length != 0)
- list.Add( sb.ToString() );
- ret = list.ToArray();
- }
- }
- }
- namespace TSVExportImporter
- {
- class MainClass
- {
- public static void Main( string[] args )
- {
- StringBuilder output = new StringBuilder();
- StringWriter w = new StringWriter(output);
- TSV.TSV.ToString( w, new[]{ "Hello,", "World!", "Complex\nNewline", "Complex\"Quote", "Complex\tTab" } );
- Console.WriteLine( "Encode:" );
- Console.WriteLine( output.ToString() );
- StringReader r = new StringReader( output.ToString() );
- string[] result;
- TSV.TSV.FromString( r, out result );
- Console.WriteLine( "Decode:" );
- foreach( string elm in result )
- Console.WriteLine( elm );
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement