您的位置:首页 > 其它

2014华为机试-字符串替换

2014-10-22 14:25 357 查看
题目要求:输入一个字符串,然后在输入一个整数,就是替换字符串的次数,然后依次输入须要替换的字符串……

比如:

输入:asdfghjasdfghj

3

as->bnm

df->qwe

gh->yui

输出:bnmqweyuijbnmqweyuij

意思就是,将输入的字符串中,as替换成bnm,df替换成qwe,gh替换成yui,总共替换三次,注意次数是不限定的,能够是随意整数等。

假设输入的次数是2,举例说明:

输入:asdfgasdfg

2

as->bn

df->yuio

输出:bnyuiogbnyuiog

做完这道题,感觉自己把自己坑了,选择了用C语言,事实上学过Java的同学随便都能够用几行代码实现,耗掉自己非常多时间。

程序实现例如以下:

/*
** Replace String
*/
#include <stdio.h>
#include <string.h>

#define SUCCESS		0
#define FAILED		-1
#define MAXLINE		48
#define NOTFOUND	-1

int GetNumber(void)
{
char temp;
int count;
count = 0;

temp = getchar();
while(temp >= '0' && temp <= '9')
{
count = count * 10 + (temp - 0x30);
temp = getchar();
}
return count;
}

void GetString(char buff[])
{
char temp;
int i;
i = 0;

temp = getchar();
while (temp != '\n')
{
buff[i++] = temp;
temp = getchar();
}
buff[i] = '\0';
}

int FindString(int begin, char str1[], char str2[])
{
int i, j;
int MAXSIZE = strlen(str2);
i = begin;
while (str1[i] != '\0')
{
for (j = 0; j < MAXSIZE; j++)
{
if (str1[i++] == str2[j])
continue;
else break;
}
if (j == MAXSIZE)
return (i - j);
}
return NOTFOUND;
}

int myStrcpy(char dest[], char src[])
{
int i = 0;

while (src[i] != '\0')
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
return SUCCESS;
}

void StringSplite(char *pBuff, char target[], char repStr[])
{
int i = 0, j = 0;
while(*(pBuff + i) != '-')
{
target[i] = *(pBuff + i);
i++;
}
target[i] = '\0';

while (*(pBuff + i) == '-' || *(pBuff + i) == '>')
i++;

while (*(pBuff + i) != '\0')
{
repStr[j++] = *(pBuff + i);
i++;
}
repStr[j] = '\0';
}

void ReplaceString(char dest[], char src[], char repStr[])
{
char temp[MAXLINE] = {'\0'};
int Swidth, Rwidth;
int begin = 0, iPos = 0;
int i = 0;

Swidth = strlen(src);
Rwidth = strlen(repStr);

while (dest[i] != '\0')
{
iPos = FindString(begin, dest, src);
if (iPos != NOTFOUND)
{
myStrcpy(temp, dest + iPos + Swidth);
myStrcpy(dest + iPos, repStr);
myStrcpy(dest + iPos + Rwidth, temp);

memset(temp, 0, MAXLINE);
begin = iPos + Rwidth;
i = begin;
}
else
break;
}
}

int main(void)
{
char **pChar = NULL;
char inData[48] = {'\0'};
char target[10] = {'\0'};
char repStr[10] = {'\0'};
int i, j, sum;

GetString(inData);
fflush(stdin);
sum = GetNumber();

pChar = (char **) malloc(sum * sizeof(char *));
if (pChar == NULL)
{
printf("Malloc memory for pChar has faild!\n");
return 0;
}
for (i =0; i < sum; i++)
{
*(pChar + i) = (char *) malloc(MAXLINE * sizeof(char));
if (*(pChar + i) == NULL)
{
printf("Malloc memory for *(pChar + %d) has faild!\n", i);
return 0;
}
}

for (i = 0; i < sum; i++)
{
fflush(stdin);
GetString(*(pChar + i));
}

for (i = 0; i < sum; i++)
{
memset(target, 0, sizeof(target));
memset(repStr, 0, sizeof(repStr));
StringSplite(*(pChar + i), target, repStr);
ReplaceString(inData, target, repStr);
}
printf("%s\n", inData);

for (i = 0; i < sum; i++)
free(*(pChar + i));
free(pChar);
return 0;
}


执行结果例如以下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: