【问题标题】:Get specific char from a string request从字符串请求中获取特定字符
【发布时间】:2016-05-13 15:38:53
【问题描述】:

我需要从一个字符串中获取 4 个变量

这是某人可以向服务器提出的请求:

String request= "Jouer_un_bulletin <nbT> <mise> <numeros_grilleA> <numeros_grilleB>"

我需要得到nbtmisenumeros_grilleAnumeros_grilleB

【问题讨论】:

  • string Jouer_un_bulletin 与 4 个结果有何关联?
  • @Ian 有并发出 qith 帖子。我现在用“”替换了
  • 您最好按原样编辑问题,然后通过将&lt; &gt; 编写为代码使其可见(按 ctrl +k )
  • @Ian 谢谢我已经改了!

标签: c# substring


【解决方案1】:

您可以尝试使用正则表达式

  String request = "Jouer_un_bulletin <nbT> <mise> <numeros_grilleA> <numeros_grilleB>";

  String pattern = @"(?<=<)[^<>]*(?=>)";

  String[] prms = Regex
    .Matches(request, pattern)
    .OfType<Match>()
    .Select(match => match.Value)
    .ToArray();

测试:

  // nbT
  // mise
  // numeros_grilleA
  // numeros_grilleB
  Console.Write(String.Join(Environment.NewLine, prms));

【讨论】:

    【解决方案2】:

    您需要解析请求。如何做到这一点完全取决于您期望收到的内容以及您如何验证它。假设(这是一个很大的假设)你总是会得到上面的格式,你可以使用 String.Split 在左括号字符上拆分字符串,然后取出组件(忽略第一个)并修剪掉右括号和任何额外的空格。这些将是您的变量。无论如何,这都不是发送数据的好方法,您至少应该在使用之前对这些数据进行大量验证。

    最基本的(无论如何这是你不应该使用的糟糕代码)概念是:

     String request= "Jouer_un_bulletin <nbT> <mise> <numeros_grilleA> <numeros_grilleB>";
     var pieces = request.Split('<');
     var strList = new List<string>();
     for(int i = 1 ; i < pieces.Length; i++)
     {
         strList.Add(pieces[i].Trim(' ','>'));
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-20
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      相关资源
      最近更新 更多