替换空格

1. java版本:

public static String replaceSpace(StringBuffer str) {
        String answer="";
        String originalStr=str.toString();
        int length=originalStr.length();
        int replaceIndex=originalStr.indexOf(" ");
        while(replaceIndex!=-1){
            answer+=originalStr.substring(0,replaceIndex);
            answer+="%20";
            originalStr=originalStr.substring(replaceIndex+1,length);
            replaceIndex=originalStr.indexOf(" ");
            length=originalStr.length();
        }
        answer+=originalStr;

        return answer;
    }

2. C++版本:

void replaceSpace(char *str, int length) {
	int spaceNumber = 0;
	for (int i = 0; i < length; i++) {
		if (str[i] == ' ') {
			spaceNumber++;
		}
	}
	int newLength = length + spaceNumber * 2;
	int pointForNewStr = newLength;
	int pointForOldStr = length;
	while (pointForOldStr >= 0 && pointForOldStr != pointForNewStr) {
		char currentChar = str[pointForOldStr--];
		if (currentChar == ' ') {
			str[pointForNewStr--] = '0';
			str[pointForNewStr--] = '2';
			str[pointForNewStr--] = '%';
		}
		else {
			str[pointForNewStr--] = currentChar;
		}
	}
}

 

你可能感兴趣的:(代码,java,剑指offer(牛客))