Created
November 28, 2018 15:36
-
-
Save minikuma/c5728681a931b1cb0def7572d00348b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class URLreplace { | |
static String replaceSpaces(String s, int len) { | |
int spaceCount = 0, index, i = 0; | |
char[] originStr = s.toCharArray(); | |
for (i = 0; i < len; i++) { | |
if (originStr[i] == ' ') { | |
spaceCount++; | |
} | |
} | |
index = len + spaceCount * 3; // 공백 -> %20, 공백문자별로 3배의 저장공간 필요 | |
//결과를 복사할 배열 공간 | |
char[] result = new char[index]; | |
//기존 배열의 값을 새로운 배열 공간에 복사 | |
for (i = len - 1; i >= 0; i--) { | |
//공백 치환 | |
if (originStr[i] == ' ') { | |
result[index - 1] = '0'; | |
result[index - 2] = '2'; | |
result[index - 3] = '%'; | |
index = index - 3; | |
} | |
else { | |
result[index - 1] = originStr[i]; | |
index--; | |
} | |
} | |
StringBuilder sb = new StringBuilder(); | |
for (i = 0; i < result.length; i++) { | |
sb.append(result[i]); | |
} | |
return sb.toString(); | |
} | |
public static void main(String[] args) { | |
System.out.println(replaceSpaces("Mr John Smith", 14)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment