【问题标题】:While loop for an index existing现有索引的 While 循环
【发布时间】:2012-05-26 22:59:47
【问题描述】:

我怎样才能写出如下语句(伪代码)的 while 循环:

While the index of "blahblah" in string 1 exists

do this

【问题讨论】:

  • 你的伪代码几乎是真正的 C#。为什么不自己学习如何用 C# 编写它呢?

标签: c# while-loop indexof


【解决方案1】:
while(string1.Contains("blahblah")) {
    // do this
}

成功编译为 C# 的伪代码。 0 个错误,0 个警告。所用时间:0:00:01.860。

【讨论】:

  • 有趣,这与if(string1.Contains("blahblah")) while(true){ DoThis();} 非常相似,并且永远循环......
  • @agent-j:如果string1 是从DoThis() 修改的,则不会。
【解决方案2】:
  var string1 = "blahblah blahblah blahblah blahblah ";
  int pos = -1;
  while (0 >= (pos = string1.IndexOf("blahblah", pos + 1)))
  {
     // do this.
  }

【讨论】:

  • 请注意,这总是至少执行一次,即使 string1 不包含任何 blahblahs。另外,我认为您正在假设 OP 想要什么,而我并没有真正从这个问题中得到什么。这看起来更像是“为 string1 中的每个 blahblah 执行一次”。也许这是对的。
  • @Blorgbeard Oops.. 我引入了一个错误,试图使以前的代码更优雅。谢谢...已修复。
猜你喜欢
  • 2020-10-10
  • 2018-04-19
  • 1970-01-01
  • 2022-01-22
  • 2021-06-22
  • 2019-02-01
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
相关资源
最近更新 更多