去哪網 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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章