您可以通過獲取句子,這是由分隔的單詞組開始了「」字符,然後爲每個句子獲取單詞,這些單詞由空白字符分隔。
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Diagnostics;
String^ originalString = "This is a chord. This is another. This is a third. Now form a band.";
// This array contains the sentences, which are separated by '.'
array<String^>^ sentences = originalString->Split(
gcnew array<String^> { "." },
StringSplitOptions::RemoveEmptyEntries);
Debug::Assert(sentences->Length == 4);
// This list contains individual words for all sentences.
List<String^>^ words = gcnew List<String^>();
for each(String^ sentence in sentences) {
words->AddRange(sentence->Split(
gcnew array<String^> { " " },
StringSplitOptions::RemoveEmptyEntries));
}
Debug::Assert(words->Count == 15);
for each(String^ word in words) {
Console::WriteLine(word);
}
但是,如果你有興趣的唯一的事情是個人話,您可以使用讓他們在一個單一的表達LINQ:
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Diagnostics;
using namespace System::Linq;
System::String^ StripDot(System::String^ input) {
return input->Replace(".", "");
}
void Test()
{
String^ originalString = "This is a chord. This is another. This is a third. Now form a band.";
IEnumerable<String^>^ words = Enumerable::Select<String^,String^>(
originalString->Split(
gcnew array<String^> { " " },
StringSplitOptions::RemoveEmptyEntries),
gcnew Func<String^,String^>(StripDot));
Debug::Assert(Enumerable::Count(words) == 15);
for each(String^ word in words) {
Console::WriteLine(word);
}
}
這是一個很好的例子,但是我在每個句子中都需要一些單詞。所以根據你的String ^文本,我應該得到答案4; 3; 4; 4. –
這個信息不包括在你的問題中,不是很清楚,所以我不知道它; - ] – t3chb0t
@DeividasKiznis我更新了我的答案。你可以檢查新的解決方案是否滿足你的要求;-) – t3chb0t