回复 10楼 ehszt
i, love you.the words number is 3
i
love
you
请按任意键继续. . .
这是我运行的结果,可以识别,忘了告诉你,我的程序只能识别,。和空格
程序代码:
/*
C++/CLR 版本
編譯:VS中創建C++/CLR項目,或在命令行中用cl /clr參數編譯
*/
using namespace System;
int main(array<String^>^ args)
{
// 分割符清單
array<Char>^ DelimitChar_Array = { ' ', ',', '!', '.', '?', '\'', '\"' };
Console::WriteLine(L"請輸入一行文本,回車結束:");
String^ text = Console::ReadLine();
Console::WriteLine("\n結果:");
// 獲得分割單詞數組(第二個參數表示在結果中移除空串)
array<String^>^ arrSplit = text->Split(DelimitChar_Array, StringSplitOptions::RemoveEmptyEntries);
// 遍歷數組輸出結果
for each (String^ word in arrSplit)
{
Console::WriteLine(L"{0}", word);
}
Console::ReadKey(true);
return 0;
}

程序代码:
/*
C++11版本
編譯:VS(或其他支持C++11標準的編譯器)中創建C++控制臺項目,或在命令行中用cl編譯
*/
#include <iostream>
#include <string>
#include <vector>
#include <conio.h>
const char DelimitChar_Array[] = { ' ', ',', '!', '.', '?', '\'', '\"' };
std::vector<std::string> Split(const std::string& text, const char* delimits)
{
std::vector<std::string> result;
std::string::size_type beginIndex, endIndex;
beginIndex = text.find_first_not_of(delimits);
while (beginIndex != std::string::npos)
{
endIndex = text.find_first_of(DelimitChar_Array, beginIndex);
if (endIndex == std::string::npos)
{
endIndex = text.length();
}
result.push_back(std::string(text, beginIndex, endIndex - beginIndex));
beginIndex = text.find_first_not_of(DelimitChar_Array, endIndex);
}
return result;
}
int main(void)
{
std::cout << "請輸入一行文本,回車結束:" << std::endl;
std::string text;
if (std::getline(std::cin, text))
{
std::cout << "結果:" << std::endl;
std::vector<std::string> arrSplit = Split(text, DelimitChar_Array);
for (std::string word : arrSplit)
{
std::cout << word << std::endl;
}
}
_getch();
return 0;
}
[此贴子已经被作者于2016-1-4 02:41编辑过]

程序代码:
/*
C 版本(C++編譯器C風格代碼)
編譯:VS中創建C++控制臺項目,或在命令行中用cl編譯
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
const size_t MAX_LENGTH = 80; // 字符串最大寛度
const size_t MAX_WORD_NUMBER = 50; // 最大單詞數
const char DelimitChar_Array[] = { ' ', ',', '!', '.', '?', '\'', '\"', '\n', '\0' };
size_t Split(const char* text, size_t size, char result[][MAX_LENGTH + 1])
{
char* buffer = (char*)malloc(size);
strncpy_s(buffer, size, text, size);
size_t count = 0;
char* next_token;
char* token = strtok_s(buffer, DelimitChar_Array, &next_token);
while (token)
{
strncpy_s(result[count++], MAX_LENGTH + 1, token, MAX_LENGTH + 1);
token = strtok_s(NULL, DelimitChar_Array, &next_token);
}
free(buffer);
return count;
}
int main(void)
{
printf_s("請輸入一行文本,回車結束:\n");
char text[MAX_LENGTH + 1];
fgets(text, MAX_LENGTH + 1, stdin);
if (text[0] != '\n')
{
printf_s("結果:\n");
char arrSplit[MAX_WORD_NUMBER][MAX_LENGTH + 1];
const size_t count = Split(text, MAX_LENGTH + 1, arrSplit);
for (size_t i = 0; i < count; ++i)
{
printf_s("%s\n", arrSplit[i]);
}
}
_getch();
return 0;
}
