iT邦幫忙

0

請教各位高手,使用C或Python設計一個isSubstring函數,給予兩個字串s1 and s2,函數會檢查s1是否為s2的子字串。

  • 分享至 

  • xImage

請問各位大大,該如何寫呢?謝謝。
設計一個isSubstring函數,給予兩個字串s1 and s2,函數會檢查s1是
否為s2的子字串。假如是,回傳1,否則回傳0。
Examples :
Input : s1 = “row", s2 = “tomorrow"
Output : 1
Input : s1 = "practice", s2 = "tomorrow "
Output : 0.

你起碼要說是哪種程式語言吧.程式語言有很多種,你這樣叫人怎樣幫你.
ccutmis iT邦高手 2 級 ‧ 2020-03-25 12:20:04 檢舉
我覺得可能是作業,一般常見的程式語言都有substring這類的函式,不需要重新造輪子才對。
froce iT邦大師 1 級 ‧ 2020-03-25 17:28:04 檢舉
作業自己寫,
然後出這題說可以用python的一定把python當c寫。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
listennn08
iT邦高手 5 級 ‧ 2020-03-25 13:17:31
最佳解答

這樣 ?

# python
def isSubstring(s1, s2):
    return 1 if s1 in s2 else 0
# 自刻的話...
def isSubstring(s1, s2):
    if len(s1) > len(s2): return 0
    for i in range(len(s2)):
        for j in range(i, len(s2)):
            if s1 == s2[i:j+1]:
                return 1
    return 0
/** C */
int isSubstring(char* s1, char* 2)
{
    return strstr(s2, s1) != NULL ? 1 : 0;
}
/** C 找了範例直接改... */
int isSubstring(char *s1, char *s2)
{
    while (*s2) 
	{
	    char *Begin = s2;
		char *pattern = s1;
		    
		// If first character of sub string match, check for whole string
		while (*s2 && *pattern && *s2 == *pattern) 
		{
		    s2++;
			pattern++;
		}
		// If complete sub string match, return starting address 
		if (!*pattern)
			return 1;
		    	  
		s2 = Begin + 1;	// Increament main string 
	}
	return 0;
}
1
海綿寶寶
iT邦大神 1 級 ‧ 2020-03-25 13:22:29
set "row" to s1
set length of s1 to len1
set "tomorrow" to s2
set length of s2 to len2
set 0 to result

if len1 > len2
   set 0 to result
else
   for i = 1 to len2-len1+1
      extract s2 range from char at position i to char at position (i+len1-1) to str
      if str equals to s1 then
         set 1 to result
      end if
   end for
end if

write result to output
yiwen6761 iT邦新手 5 級 ‧ 2020-03-26 14:03:31 檢舉

感謝大神

我要發表回答

立即登入回答