POJ——字符串插入

总时间限制: 
1000ms 
内存限制: 
65536kB
描述
有两个字符串str和substr,str的字符个数不超过10,substr的字符个数为3。(字符个数不包括字符串结尾处的'\0'。)将substr插入到str中ASCII码最大的那个字符后面,若有多个最大则只考虑第一个。
输入
输入包括若干行,每一行为一组测试数据,格式为
str substr
输出
对于每一组测试数据,输出插入之后的字符串。
样例输入
abcab eee
12343 555
样例输出
abceeeab
12345553

 1 # include<stdio.h>
 2 # include<string.h>
 3 
 4 int main(void)
 5 {
 6     char s1[11], s2[4];
 7     int i;
 8     while(scanf("%s%s", s1, s2)!=EOF)
 9     {
10         int max=0;
11         int len=strlen(s1);
12         for(i=0; i<len; i++)
13         {
14             if(s1[i]>s1[max])
15             {
16                 max=i;
17             }
18         }
19         for(i=0; i<=max; i++)
20         printf("%c", s1[i]);
21         printf("%s", s2);
22         for(i=max+1; i<len; i++)
23         printf("%c", s1[i]);
24         printf("\n");
25     }
26 
27     return 0;
28 }

 

 

 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 const int MAX_STRING_LEN = 15;
 5 
 6 bool readLine(char *str, char *substr)
 7 {
 8     bool bEof = false;
 9 
10     if (2 == fscanf(stdin, "%s %s", str, substr))
11     {
12         bEof = true;
13     }
14 
15     return bEof;
16 }
17 
18 void insert(char *str, char *substr)
19 {
20     int i, maxIdx;
21     size_t size = strlen(str);
22 
23     // find the index of the maximum ascii code
24     maxIdx = 0;
25     for (i=1; i<size; ++i)
26     {
27         if (str[maxIdx] < str[i])
28         {
29             maxIdx = i;
30         }
31     }
32 
33     // shift right to make space 
34     for (i=size; i>maxIdx; --i)
35     {
36         str[i+3] = str[i];
37     }
38 
39     // insert the substr
40     ++i;
41     str[i++] = substr[0];
42     str[i++] = substr[1];
43     str[i]   = substr[2];
44 }
45 
46 void print(char *str)
47 {
48     printf("%s\n", str);
49 }
50 
51 int main(void)
52 {
53     char str[MAX_STRING_LEN]    = {'\0'};
54     char substr[MAX_STRING_LEN] = {'\0'};
55 
56     while (readLine(str, substr))
57     {
58         insert(str, substr);
59         print(str);
60     }
61 
62     return 0;
63 }

 

欢迎来我的个人网站:http://www.rxwcv.cn
posted @ 2013-11-24 11:29  Hewie_Bai  阅读(834)  评论(0编辑  收藏  举报