C++/CLI - 拆分具有未知空格数的字符串作为分隔符



我想知道如何(以及最好以哪种方式)在 C++/CLI 中拆分具有未知数量空格的字符串作为分隔符?

编辑:问题是空格号未知,所以当我尝试使用这样的拆分方法时:

String^ line;
StreamReader^ SCR = gcnew StreamReader("input.txt");
while ((line = SCR->ReadLine()) != nullptr && line != nullptr)
{
     if (line->IndexOf(' ') != -1)
        for each (String^ SCS in line->Split(nullptr, 2))
        {
            //Load the lines...
        }
}

这是输入.txt的外观示例:

ThisISSomeTxt<space><space><space><tab>PartNumberTwo<space>PartNumber3
当我尝试运行程序时,加载的第一行是"ThisISSomeTxt",加载的第二行是"(无),加载的第三行也是"

(无),第四行也是"无,加载的第五行是"PartNumberTwo",第六行是PartNumber3。

我只希望加载ThisISSomeTxt和PartNumberTwo:?我该怎么做?

为什么不直接使用 System::String::Split(..)?

下面的代码示例取自 http://msdn.microsoft.com/en-us/library/b873y76a(v=vs.80).aspx#Y0 ,演示如何使用 Split 方法标记字符串。

using namespace System;
using namespace System::Collections;
int main()
{
   String^ words = "this is a list of words, with: a bit of punctuation.";
   array<Char>^chars = {' ',',','->',':'};
   array<String^>^split = words->Split( chars );
   IEnumerator^ myEnum = split->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      String^ s = safe_cast<String^>(myEnum->Current);
      if (  !s->Trim()->Equals( "" ) )
            Console::WriteLine( s );
   }
}

我认为你可以用String.Split方法做你需要做的事情。

首先,我认为您期望"count"参数的工作方式不同:您正在传入2,并期望返回第一个和第二个结果,并期望丢弃第三个结果。它实际返回的是第一个结果,第二个和第三个结果连接成一个字符串。如果您只需要ThisISSomeTxtPartNumberTwo,则需要在前 2 个之后手动丢弃结果。

据我所知,您不希望返回字符串中包含任何空格。如果是这样的话,我认为这就是你想要的:

String^ line = "ThisISSomeTxt   tPartNumberTwo PartNumber3";
array<String^>^ split = line->Split((array<String^>^)nullptr, StringSplitOptions::RemoveEmptyEntries);
for(int i = 0; i < split->Length && i < 2; i++)
{
    Debug::WriteLine("{0}: '{1}'", i, split[i]);
}

结果:

0: 'ThisISSomeTxt'
1: 'PartNumberTwo'

最新更新