模拟字符串拆分函数



>我创建了一个拆分函数:句子中的每个单词都作为元素添加到string数组中。

我对最后一个单词有问题;它没有添加到输出数组中:

代码:

// the funcion
static void splits(string str)
{
   int i=0;
   int count=0;
   string[] sent = new string[2];
   string buff= "";
   while (i < str.Length)
   {
      if (str[i] == ' ')
      {
         sent[count] = buff;
         count++;
         buff = "";
      }
      buff += str[i];
      i++;
   }
     Console.WriteLine(sent[0]);
}

// When used
splits("Hello world!");

-----------------------------------------------


我找到了解决方案,这很简单
希望大家受益

static void splits(string str)
{
  int i = 0;
  int count = 0;
  string[] sent = new string[2];
  string buff = "";
  str += " ";         // the solution here, add space after last word
  while (i < str.Length)
  {
    if (str[i] == ' ')
    {
       sent[count] = buff;
       count++;
       buff = "";
    }
    buff += str[i];
    i++;
  }
  for (int z = 0; z < sent.Length; z++)
  {
     Console.WriteLine(sent[z].Trim());
  }
}
结果

将如下所示(此处为视觉结果)

Hello  
world!

退出 while 循环后,需要手动添加剩余字符作为数组中的最后一个条目。 这是因为您在字符(空格)上进行了拆分,但最后一个单词后面没有空格来表示要添加的单词:

...
}
if (!string.IsNullOrEmpty(buff))
    sent[count++] = buff;

样品:http://ideone.com/81Aw1


但是,正如CC_4指出的那样,除非您有一些需要实现的特殊功能,否则您应该只使用内置的split函数:

"Hello World!".Split(' ');

这在一行代码中开箱即用,并且已经由 .NET Framework 的开发人员和无数用户进行了详尽的测试。

完成

while 循环后,您需要检查缓冲区,以确定最后一个单词是否仍然存在。此外,您只打印第一个元素。

// the funcion
static void splits(string str)
{
   int i=0;
   int count=0;
   string[] sent = new string[2];
   string buff= "";
   while (i < str.Length)
   {
      if (str[i] == ' ')
      {
         sent[count] = buff;
         count++;
         buff = "";
      }
      buff += str[i];
      i++;
   }
   if (buff.Length > 0) {
       sent[count] = buff;
       count++;
   }
   for (i = 0; i < count; i++)
       Console.WriteLine(sent[i]);
}
if (str[i] == ' ')

永远不会为最后一句话开火

while (i < str.Length)
{
   if (str[i] == ' ')
   {
      sent[count] = buff;
      count++;
      buff = "";
   }
   else
   {
       buff += str[i];
   }
   i++;
}
sent[count] = buff;

为了使解决方案可重用,我首先计算了空格数;我还将最后一个单词作为特例处理(因此,这使得它适用于不包含空格的输入)。应该很容易将其调整为适用于任何分隔符。

  string s = "Test spaces in a sentence :)";
  int numSpaces = 1;
  foreach (char c in s)
  {
    if (c == ' ')
    {
      ++numSpaces;
    }
  }
  string[] output = new string[numSpaces];
  int spaceIndex = s.IndexOf(' ');
  int index = 0;
  int startIndex = 0;
  --numSpaces;
  while (index < numSpaces)
  {
    output[index] = s.Substring(startIndex, spaceIndex - startIndex);
    startIndex = spaceIndex + 1;
    spaceIndex = s.IndexOf(' ', startIndex);
    ++index;
  }
  output[index] = s.Substring(startIndex);
  foreach (string str in output)
  {
    Console.WriteLine(str);
  }

为什么不是这样的东西?

 private Array SplitSentence(string splitMe)
 {
   if(string.IsNullOrEmpty(splitMe)) return null;
   var splitResult = splitMe.Split(" ".ToArray());
   return splitResult;
 }

最新更新