Algorithm: replace spaces

Problem Description

Replace spaces: Please implement a function to replace each space in the string s with "%20".
Input: s = "We are happy."
Output: "We%20are%20happy."

solution

The first, this is the method that I thought of when I got the title. I directly call the replace() method, and the replacement is over. Later I found that something was wrong and the array would be out of bounds.
The second is to call the StringBuffer class, use some of the methods in it to manipulate the array, and finally output the array. This method is relatively intuitive, but still does not meet the meaning of the question, and the problem of array out of bounds will occur.
The third type is to define an array first, the length of which is three times the original string, then define a variable, traverse the array, every time a space is encountered, the variable increments by 3, the character is output, and finally the array is converted to String.

Code

        String s = "We are happy.";
		//第一种方法 
        s=s.replace(" ","%20");
        System.out.println(s);

		//第二种方法
        StringBuffer sb= new StringBuffer();
        for(int i = 0 ; i < s.length(); i++){
    
    
            char c = s.charAt(i);
            if(c == ' ') {
    
    
                sb.append("%20");
            }
            else {
    
    
                sb.append(c);
            }
        }
        System.out.println(sb);

		 
        //第三种方法
        int i = s.length();
        int nums = 0;
        char[] arr = new char[i*3];
        for (int l=0;l<i;l++){
    
    
            char c = s.charAt(l);
            if (c==' '){
    
    
                nums += 3;
                arr[--nums] = '0';
                arr[--nums] = '2';
                arr[--nums] = '%';
                nums += 3;
            }else{
    
    
                arr[nums] = c;
                nums +=1;
            }
        }
        s = String.valueOf(arr);
        System.out.println(s);

to sum up

The first method does not meet the meaning of the question. The second and third methods are basically the same in terms of thinking. They both locate the space first and then perform the conversion, but there is a big difference in the order of operations. The second method does not pay attention to the length of the array, and it is easy to cause the problem of array out of bounds. The third method defines three times the length of the array in advance (the reason for defining three times the length is because if the string is all spaces, Then the length after the conversion is three times the original length), let the variable increase by itself, and finally convert it into a string.

Guess you like

Origin blog.csdn.net/weixin_46687295/article/details/106450307