一道很是简单的小题,可是要注意的是时间问题。c中对于字符串的打印时间要低于对单个字符打印的时间。故在输出时要注意。 java
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { void replace(char*, char*); char* c = (char *) malloc(sizeof(char) * 1000001); char* result = (char *) malloc(sizeof(char) * 1000001); while (gets(c) != NULL) { replace(c, result); printf("%s\n", result); //Linux下系统有缓存,window中不用考虑缓存 //刷新缓存 fflush(stdout); } free(c); return EXIT_SUCCESS; } void replace(char* c, char* result) { while (*c != '\0') { if (*c != ' ') { *result++ = *c++; } else { *result++ = '%'; *result++ = '2'; *result++ = '0'; c++; } } }下面这个方式会超时
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char* c = (char *) malloc(sizeof(char) * 1000001); while (gets(c) != NULL) { int i = 0; int len = strlen(c); for (; i < len; i++) { char ch = *(c + i); if (ch != ' ') { printf("%c", ch); } else { printf("%%20"); } //Linux下系统有缓存,window中不用考虑缓存 //刷新缓存 fflush(stdout); } printf("\n"); } return EXIT_SUCCESS; }使用Java时要注意:Scanner 不能读入一整行空格“ ”;
import java.util.Scanner; public class Main { /** * 方法名称:main() * 方法描述: * @param * @return String * @Exception */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in).useDelimiter("\\.+"); while(scanner.hasNext()){ String str = scanner.nextLine(); str = str.replaceAll(" ", "%20"); System.out.println(str); } } }