代码之家  ›  专栏  ›  技术社区  ›  Mark Denom

如何获得不同情况下的特定子字符串

  •  0
  • Mark Denom  · 技术社区  · 7 年前

    我正在尝试获取用户名 大块

    static void Main(string[] args)
            {
                List<string> Lines  = new List<string>()
                {
                    "[20:03:01 INFO]: UUID of player MyUsername123 is b87e1cbc-c67c-4026-a359-8659de8b4",
                    "[21:03:10 INFO]: UUID of player Cool_Username is b7ecbc-c67c-4026-a359-8652f9de8b4",
                    "[22:23:10 INFO]: UUID of player theuserN4m3 is b87eabc-c67c-4026-a359-8652ad9dssdse8b4",
                    "[20:08:10 INFO]: UUID of player WhatANiceUsername is b87g1cbc-c67c-4026-a359-8652agde8b4",
    
                };
    
                foreach (var line in Lines)
                {
                    //Get the username part
                }
            }
    

    用户名将是 MyUsername123 , Cool_Username theuserN4m3 , WhatANiceUsername

    4 回复  |  直到 7 年前
        1
  •  4
  •   Levon Ravel    7 年前

    执行按空格分割的字符串,包含数组索引5将包含用户名。

    public void SplitExample()
    {
        List<string> Lines = new List<string>()
        {
           "[20:03:01 INFO]: UUID of player MyUsername123 is b87e1cbc-c67c-4026-a359-8659de8b4",
           "[21:03:10 INFO]: UUID of player Cool_Username is b7ecbc-c67c-4026-a359-8652f9de8b4",
           "[22:23:10 INFO]: UUID of player theuserN4m3 is b87eabc-c67c-4026-a359-8652ad9dssdse8b4",
           "[20:08:10 INFO]: UUID of player WhatANiceUsername is b87g1cbc-c67c-4026-a359-8652agde8b4",
        };
    
        foreach(var i in Lines)
        {
           var splitArray = i.Split(' ');
           Console.WriteLine(splitArray[5]);
        }
    }
    
        2
  •  4
  •   Brandon    7 年前

    space 字符,然后抓取用户名字段的索引(因为您说过它总是在同一个位置)。

    foreach (var line in Lines)
    {
        string[] trimmed = line.Split(' ');
        string username = trimmed[5];
    }
    

    您可能希望在错误处理方面做得更好一些,但这应该可以让您开始。

        3
  •  0
  •   maccettura    7 年前

    字符串本质上是一个 IEnumerable<char> Skip() TakeWhile() Linq中用于从字符串中提取用户名的扩展方法:

    var usernames = lines.Select(
        line => new String(line.Skip(32).TakeWhile(c => !char.IsWhiteSpace(c)).ToArray()));
    

    不停摆弄 here

        4
  •  0
  •   Flydog57    7 年前

    另一种LINQ ish解决方案:

      List<string> lines = new List<string>()
      {
          "[20:03:01 INFO]: UUID of player MyUsername123 is b87e1cbc-c67c-4026-a359-8659de8b4",
          "[21:03:10 INFO]: UUID of player Cool_Username is b7ecbc-c67c-4026-a359-8652f9de8b4",
          "[22:23:10 INFO]: UUID of player theuserN4m3 is b87eabc-c67c-4026-a359-8652ad9dssdse8b4",
          "[20:08:10 INFO]: UUID of player WhatANiceUsername is b87g1cbc-c67c-4026-a359-8652agde8b4",
      };
    
      IEnumerable<string> players = from line in lines select line.Split(' ')[5];