去哪网 2014.9.25 笔试题
第一题:
public static String overlay(String str, String overlay, int start, int end)
用字符串overlay覆盖字符串str从start到end之间的串。
如果str为null,则返回null
如果start或end小于0,则设为0
如果start大于end,则两者交换
如果start或end大于str的长度,则认为等于str的长度
举例(*表示任意):
StringUtils.overlay(null, *, *, *) = null
StringUtils.overlay("","as",0,0)) = "as"
StringUtils.overlay("asdfgh","qq",2,5)) = "asqqh"
StringUtils.overlay("asdfgh","qq",5,2)) = "asqqh"
StringUtils.overlay("asdfgh","qq",-1,3)) = "qqfgh"
StringUtils.overlay("asdfgh","qq",-1,-3)) = "qqasdfgh"
StringUtils.overlay("asdfgh","qq",7,10)) = "asdfghqq"
StringUtils.overlay("asdfgh","qq",0,8)) = "qq"
StringUtils.overlay("asdfgh","qq",2,8)) = "asqq"
StringUtils.overlay("asdfgh",null,2,5)) = "ash"
StringUtils.overlay("asdfgh","",2,5)) = "ash"
大意如此.
代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> char *overlay_fun(char *str, char *overlay, int start, int end) { char *copy = malloc(strlen(str)*sizeof(char)); int i = 0; int j = 0; if(strlen(str) == 0) return NULL; if(start < 0) start = 0; if(end < 0) end = 0; if(start > end) { int tmp; tmp = start; start = end; end = tmp; } if(start > strlen(str)) start = strlen(str); if(end > strlen(str)) end = strlen(str); for(i = 0; i < start; i++) { copy[i] = str[i]; } copy[i] = '\0'; while(overlay[j] != '\0') { copy[i] = overlay[j]; j++; i++; } while(str[end] != '\0') { copy[i] = str[end]; end++; i++; } str = copy; return copy; }