In network programming, assuming that the URL contains special characters, such as spaces, ' # ', and so on, the server will not be able to recognize that the correct number of parameters cannot be obtained. We need to convert these special characters into characters that the server can recognize, such as converting a space into '%20 '. Given a string, convert the spaces into '%20 '. Require as high a efficiency as possible. As far as the complexity of O (n) is complete, a char array is required to store the characters, not string
Input: An original string, such as Hello World.
Output the converted string, such as Hello%20world.
Import Java.util.scanner;public class Main {public static void main (string[] args) {Scanner Scanner = new Scanner (system.i n); String str = scanner.nextline (); char[] Chararr = Str.tochararray (); int size = Chararr.length; for (char _char:chararr) { if (_char = =) { size + = 2; } } char[] NewArr = new Char[size]; for (int i = 0, j = 0; i < chararr.length; i++) { if (' '! = Chararr[i]) { newarr[j++] = Chararr[i]; } el SE { newarr[j++] = '% '; Newarr[j++] = ' 2 '; newarr[j++] = ' 0 '; } } System.out.println (New String (NEWARR));}}
Simple character substitution in Java