当前位置:网站首页>*offer--2

*offer--2

2022-07-24 00:55:00 wzf6667

Title Description

Please implement a function , Replace each space in a string with “%20”. for example , When the string is We Are Happy. The replaced string is We%20Are%20Happy.

Direct use of replace Anencephalic operation

```java
public class Solution {
    
    public String replaceSpace(StringBuffer str) {
    
    	for(int i = 0;i<str.length();i++){
    
            char c = str.charAt(i);
            if(c == ' '){
    
                str.replace(i,i+1,"%20");
            }
        }
        return str.toString();
    }
}
// Online excerpts about stringbuffer Function of , and string There are still some different . In addition, regarding immutability, there is thread safety, which should be done by itself .
StringBuffer strbf=new StringBuffer("exception");	// Create a StringBuffer Class string 
strbf.append(String s);// Appends the specified string to this character sequence .
strbf.reverse();		// Replace this character sequence with its inverted form .
strbf.delete(int start, int end);	// Remove characters from substrings of this sequence .
strbf.insert(int offset, int i);	// take  int  The string representation of the parameter is inserted into this sequence .
strbf.replace(int start, int end, String str);	// Use given  String  The characters in replace the characters in the substring of this sequence .

no need replace Move characters according to the number of spaces , Then insert "%20"

Be careful “” and '‘ The difference between ! char Should use the ’' Otherwise, an error will be reported !

class Solution {
    
public:
    void replaceSpace(char *str,int length) {
    
        int count=0;
        for(int i=0;i<length;i++){
    
            if(str[i]==' ')
                count++;
        }
        for(int i=length-1;i>=0;i--){
    
            if(str[i]!=' '){
    
                str[i+2*count]=str[i];
            }
            else{
    
                count--;
                str[i+2*count]='%';
                str[i+2*count+1]='2';
                str[i+2*count+2]='0';
            }
        }
    }
};
原网站

版权声明
本文为[wzf6667]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230539508800.html