Problem Description
Uniform Resource Identifiers (or URIs) are strings like http://icpc.baylor.edu/icpc/, mailto:foo@bar.org, ftp://127.0.0.1/pub/linux, or even just readme.txt that are used to identify a resource, usually on the Internet or a local computer. Certain characters are reserved within URIs, and if a reserved character is part of an identifier then it must be percent-encoded by replacing it with a percent sign followed by two hexadecimal digits representing the ASCII code of the character. A table of seven reserved characters and their encodings is shown below. Your job is to write a program that can percent-encode a string of characters.
Character Encoding
" " (space) %20
“!” (exclamation point) %21
“$” (dollar sign) %24
“%” (percent sign) %25
“(” (left parenthesis) %28
“)” (right parenthesis) %29
“*” (asterisk) %2a
Output
For each input string, replace every occurrence of a reserved character in the table above by its percent-encoding, exactly as shown, and output the resulting string on a line by itself. Note that the percent-encoding for an asterisk is %2a (with a lowercase “a”) rather than %2A (with an uppercase “A”).
Sample Input
Happy Joy Joy!
http://icpc.baylor.edu/icpc/
plain_vanilla
(**)
?
the 7% solution
Sample Output
Happy%20Joy%20Joy%21
http://icpc.baylor.edu/icpc/
plain_vanilla
%28%2a%2a%29
?
the%207%25%20solution
解读
输入字符串,字符串中的某字符转成带%的形式。
- " " (空格)------> %20
- “!” ------> %21
- “$” ------> %24
- “%” ------> %25
- “(” ------> %28
- “)” ------> %29
- “*” ------> %2a
思路
将输入字符串转成字符数组用toCharArray(),遍历数组,匹配字符,需要改变即改变,不变打印原数组元素。当输入字符串为“#”,退出程序。
nextLine()能读取空格,next()不可。
import java.util.*;
public class Replace {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
while(true){
String str=s.nextLine();
if(str.equals("#")) break;//输入#时,退出
char[] chars=str.toCharArray();//字符串转成字符数组
int n=str.length();
for(int i=0;i<n;i++){
switch (chars[i]){
case ' ':
System.out.print("%20");
continue;
case '!':
System.out.print("%21");
continue;
case '$':
System.out.print("%24");
continue;
case '%':
System.out.print("%25");
continue;
case '(':
System.out.print("%28");
continue;
case ')':
System.out.print("%29");
continue;
case '*':
System.out.print("%2a");
continue;
default:
System.out.print(chars[i]);
}
}
System.out.println();
}
}
}