forked from kdn251/interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReplaceSpaces.java
30 lines (28 loc) · 899 Bytes
/
ReplaceSpaces.java
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
// Write a method to replace all spaces in a string with '%20.' You may assum ethat the string
// has sufficient space at th eend of the string to hold the additional characters, and that you
// are given the "true" length of the string. (Note: if implementing in Java, please use a characters
// array so that you can perform this operation in place)
public class ReplaceSpaces {
public void replaceSpaces(char[] str, int length) {
int spaceCount = 0, newLength; i;
for(int i = 0; i < length; i++) {
if(str[i] == ' ') {
spaceCount++;
}
}
newLength = length + spaceCount * 2;
str[newLength] = '\0';
for(int i = length - 1; i >= 0; i--) {
if(str[i] == ' ') {
str[newLength - 1] = '0';
str[newLength - 2] = '2';
str[newLength - 3] = '%';
newLength = newLength - 3;
}
else {
str[newLength - 1] = str[i];
newLength = newLength - 1;
}
}
}
}