/
githubmirror
/
interviews
Обзор
Документация
Войти
/
githubmirror
/
interviews
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
cracking-the-coding-interview/chapter-one-arrays-and-strings/ReplaceSpaces.java
30 строк
896 B
Kevin Naughton Jr
finish renaming files and directories
27 мар 2018, 19:52
27 мар 2018, 19:52
ec6dfb5
Код
Авторство
О чём код?
// Write a method to replace all spaces in a string with '%20.' You may assume that the string // has sufficient space at the end 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; 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; } } } }