//这个程序的目的是分割
字符串,把一个长字符串分割成许多
字串 //就像把一句话分割成一个一个词一样
//程序把相连的字母的数字看成一个词
//例如:输入: 234ui fb*ff
//输出: 234ui
// fb
// ff
#include<iostream>
#include<ctype.h>
#include<string.h>
bool GetWord(char* theString,
char* word, int & wordOffset);
int main()
{
const int bufferSize = 255;
char buffer[bufferSize+1];
char word[bufferSize+1];
int wordOffset = 0;
std::cout << "Enter a string: ";
std::cin.getline(buffer,bufferSize);
while (GetWord(buffer,word,wordOffset))
{
std::cout << "Got this word: " << word << std::endl;
}
return 0;
}
bool GetWord(char* theString, char* word, int& wordOffset)
{
if (!theString[wordOffset])
return false;
char *p1, *p2;
p1 = p2 = theString+wordOffset;
for (int i = 0; i<(int)strlen(p1) && !isalnum(p1[0]);i++)
p1++;
if (!isalnum(p1[0]))
return false;
p2 = p1;
while (isalnum(p2[0]))
p2++;
int len = int (p2 - p1);
strncpy (word,p1,len);
//由于
c语言中字符串是以\0结尾的,所以把生成的子串结尾赋为\0
word[len]='\0';
for (int j = int(p2-theString);j<(int)strlen(theString)&& !isalnum(p2[0]);j++)
{
p2++;
}
wordOffset = int(p2-theString);
return true;
}