Looking for C# equivalent of scanf

后端 未结 9 1123
误落风尘
误落风尘 2020-11-29 09:51

I used to code in C language in the past and I found the scanf function very useful. Unfortunately, there is no equivalent in C#.

I am using using it to

相关标签:
9条回答
  • 2020-11-29 10:45

    I have found a better solution than using sscanf from C or some rewritten part by someone (no offence)

    http://msdn.microsoft.com/en-us/library/63ew9az0.aspx have a look at this article, it explains how to make named groups to extract the wanted data from a patterned string. Beware of the little error in the article and the better version below. (the colon was not part of the group)

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string url = "http://www.contoso.com:8080/letters/readme.html";
          Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/",RegexOptions.None, TimeSpan.FromMilliseconds(150));
          Match m = r.Match(url);
          if (m.Success)
             Console.WriteLine(r.Match(url).Result("${proto}:${port}")); 
       }
    }
    // The example displays the following output: 
    //       http::8080
    
    0 讨论(0)
  • 2020-11-29 10:45

    You could use System.IO.FileStream, and System.IO.StreamReader, and then parse from there.

    0 讨论(0)
  • 2020-11-29 10:45

    Although this looks sort of crude it does get the job done:

    // Create the stream reader
    sr = new StreamReader("myFile.txt");
    
    // Read it
    srRec = sr.ReadLine();
    
    // Replace multiple spaces with one space
    String rec1 = srRec.Replace("          ", " ");
    String rec2 = rec1.Replace("         ", " ");
    String rec3 = rec2.Replace("        ", " ");
    String rec4 = rec3.Replace("       ", " ");
    String rec5 = rec4.Replace("      ", " ");
    String rec6 = rec5.Replace("     ", " ");
    String rec7 = rec6.Replace("    ", " ");
    String rec8 = rec7.Replace("   ", " ");
    String rec9 = rec8.Replace("  ", " ");
    
    // Finally split the string into an array of strings with Split
    String[] srVals = rec9.Split(' ');
    

    You can then use the array srVals as individual variables from the record.

    0 讨论(0)
提交回复
热议问题