【问题标题】:How to read between a specified character in a string?如何在字符串中的指定字符之间读取?
【发布时间】:2018-07-19 08:49:46
【问题描述】:

我试图从用户输入创建一个列表,如下所示:

Create newlist: word1, word2, word3, etc...,

但是如何仅通过使用逗号作为参考(按顺序)将它们放入数组等中来逐一获取这些单词?示例:

        string Input = Console.ReadLine();

        if (Input.Contains("Create new list:"))
        {
            foreach (char character in Input)
            {
                if (character == ',')//when it reach a comma
                {
                    //code goes here, where I got stuck...
                }
            }
        }

编辑:我不知道“拆分”我的错误的存在......但至少如果你能解释我用它来解决上述问题会很棒吗?

【问题讨论】:

  • 你知道你应该先研究,然后问问题,对吗?
  • 请添加一些代码,显示您已经尝试过的内容以及失败的地方。
  • 好的,抱歉,你能解释一下如何使用“split”吗?我什至不知道它的存在......

标签: c# string


【解决方案1】:

你可以用这个:

String words = "word1, word2, word3";

列表:

List<string> wordsList= words.Split(',').ToList<string>();

数组:

string[] namesArray = words.Split(',');

【讨论】:

    【解决方案2】:

    @patrick Artner 打败了我,但您可以只输入 split 以逗号作为参数,或者任何您想要的参数。

    这是示例,您将从文档中学习。

        using System;
    
        public class Example {
    
        public static void Main()    {
              String value = "This is a short string.";
              Char delimiter = 's';
              String[] substrings = value.Split(delimiter);
              foreach (var substring in substrings)
                 Console.WriteLine(substring);
        } 
    } 
    

    该示例显示以下输出:

    Thi 
    i 
    a 
    hort 
    tring.
    

    【讨论】:

      猜你喜欢
      • 2023-01-02
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 2018-02-28
      相关资源
      最近更新 更多