-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplaceBlank.c
More file actions
56 lines (45 loc) · 1.13 KB
/
Copy pathreplaceBlank.c
File metadata and controls
56 lines (45 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int replaceBlank(char[], int);
int main()
{
char str[4000000];
memset(str, 0, sizeof(str));
while(gets(str) != NULL){
replaceBlank(str, 4000000);
printf("%s\n", str);
}
return 0;
}
//length为字符串数组str的容量
int replaceBlank(char str[], int length)
{
if(str == NULL || length <= 0)
return -1;
int count = 0;
int indexOfOrigin = 0;
int indexOfNew = 0;
/*计算字符串中的空格个数和字符串的实际长度*/
for(int i = 0; str[i] != '\0'; i++){
++ indexOfOrigin;
if(str[i] == ' ')
count ++;
}
//计算将空格替换后的字符串实际长度,如果无空格或容量不足以存放替换后的字符串则返回-1
indexOfNew = indexOfOrigin + 2*count;
if((indexOfNew + 1 > length) || (count == 0))
return -1;
while((indexOfNew > indexOfOrigin) && (indexOfOrigin >= 0)){
if(str[indexOfOrigin] == ' '){
str[indexOfNew--] = '0';
str[indexOfNew--] = '2';
str[indexOfNew--] = '%';
}
else{
str[indexOfNew--] = str[indexOfOrigin];
}
indexOfOrigin --;
}
return 0;
}