【问题标题】:Read words from a string [duplicate]从字符串中读取单词[重复]
【发布时间】:2015-07-29 17:04:42
【问题描述】:

我有一个包含单词的字符串。例子: 字符串 s = " asd qwert 123 "; 如何使用 c# 中的循环从字符串中分别读取 asd qwert 和 123? 提前感谢

【问题讨论】:

  • 只用空格分割字符串。
  • @Shaharyar OP 想要分割空间,而不是多字符分隔符。我确定这有一个 dup,但那不是正确的。
  • String[] words = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); 然后由words迭代

标签: c# string


【解决方案1】:

如果您使用Split 方法,您可以很容易地做到这一点:

foreach(var str in s.Split(' '))
{
     // str would be one of asd, qwert and 123
     // since splitting on whitespace gives you an array 
     // with the words in the string s, which are separated one
     // from the other with a whitespace between them.  
}

请看here

【讨论】:

  • OP 可能需要使用采用StringSplitOptions 并传入StringSplitOptions.RemoveEmptyEntries 的重载
猜你喜欢
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 2021-09-23
  • 2019-07-25
  • 2017-11-09
  • 2017-02-04
  • 2012-03-14
  • 2013-08-11
相关资源
最近更新 更多