Csharp/CSharp Tutorial/String/StringReader

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Reading from a string

<source lang="csharp">using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.rupression; using System.Net; using System.Net.Mail; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; public class MainClass {

   public static void Main()
   {
   
       string contents = "Test content";
       using (StringReader reader = new StringReader(contents))
       {
           int c;
           while ((c = reader.Read()) != -1)
           {
               Console.Write("{0} ", c);
           }
       }
   }

}</source>

84 101 115 116 32 99 111 110 116 101 110 116

Reading from a string one line at a time

<source lang="csharp">using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.rupression; using System.Net; using System.Net.Mail; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; public class MainClass {

   public static void Main()
   {
   
   
       string contents = "Test content\r\nHello there";
       using (StringReader reader = new StringReader(contents))
       {
           int lineNo = 0;
           string line;
           while ((line = reader.ReadLine()) != null)
           {
               Console.WriteLine("Line#{0}: {1}", ++lineNo, line);
           }
       }
   }

}</source>

Line#1: Test content
Line#2: Hello there

Using StringReader

<source lang="csharp">using System; using System.IO; public class MainClass {

 static void Main(string[] args)
 {
   String MyString = "Hello World";
   char[] MyChar = new char[12];
   StringReader MyStringReader = new StringReader(MyString);
   MyStringReader.Read(MyChar, 0, 5);
   Console.WriteLine(MyChar);
   MyStringReader.Close();
 }

}</source>