您的位置:首页 > 其它

华为机试 — 字符串分离

2013-09-08 21:43 162 查看
题目描述:

通过键盘输入任意一个字符串序列,字符串可能包含多个子串,子串以空格分割。请编写一个程序,自动分离出各个子串,并使用','将其分离,并且在最后也补充一个',',并将子串存储。

要求实现函数:

void DivideString (const char *pInputStr, long IInputLen, char* pOutputStr );

【输入】 pInputStr: 输入字符串

IInputLen: 输入字符串长度

【输出】 pOutputStr: 输出字符串,空间已经开劈好,与输入输入字符串等长;

【注意】 只需要完成该函数功能算法,中间不需要有任何IO的输入输出

示例:

输入:"abc def ghi d"

输出:"abc,def,ghi,d"

方法1(指针):

#include <stdio.h>
#include <conio.h>

void DivideString(char *pInputStr,long IInputLen,char *pOutputStr)
{
if(!pInputStr || !pOutputStr || IInputLen<0)
return;

char *tempChar = pOutputStr;       //临时指针指向输出首地址

while(*pInputStr == ' ')//去掉字符串前的若干空格
{
pInputStr++;
}

while(*pInputStr) //第一个不为空格的字符开始循环
{
if(*pInputStr != ' ') //不为空格则将该字符复制到pOutputStr里面
{
*tempChar++ = *pInputStr++;
}
else //碰到一个或若干个空格连续着,则只在pOutputStr里面加一个',',其余忽略继续往下找
{
while(*pInputStr == ' ') //跟最开始去掉字符串前面的空格同理
{
*tempChar = ',';
pInputStr++;
}
tempChar++;
}
}

*tempChar='\0';         //结束符号

if(*(tempChar-1)!=',')  //判断最后一个是不是','
{
*tempChar = ',';
*(tempChar+1) = '\0';
}
}
int main()
{
char *c, *pIn ="  I am Bruce Lee       ";
long len=0;
c = pIn;

while(*c++)
{
len++;
}

char pOut[len];
DivideString(pIn,pOut);

printf("%s\n",pIn);
printf("%s",pOut);

getch();
return 0;
}


方法2(数组):

核心代码:

void DivideString(const char* pInputStr , long lInputLen , char* pOutputStr)
{
int i , j;
bool flag = true;

if(!pInputStr || !pOutputStr)
return;
while( pInputStr[i] == ' ') //跳过字符串前面的空格
++i;

for(j = 0 ; i < lInputLen ; ++i)
{
if(pInputStr[i] != ' ')
{
if(!flag)
flag = true;
pOutputStr[j++] = pInputStr[i]; //将各个子串分离保存下来
}
else
{
if(flag)
pOutputStr[j++] = ',';
flag = false;
}
}
pOutputStr[j++] = ',';
pOutputStr[j++] = '\0';
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: