HNCU 1746: 算法4-1,4-3:定位子串
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                HNCU 1746: 算法4-1,4-3:定位子串
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個(gè)參考.                        
                                題目描述 
 將子串在母串中第一次出現(xiàn)的位置找出來。
圖1:在母串中第pos個(gè)位置定位子串的算法
 圖2:從母串中第pos個(gè)位置獲得長度為len的子串
輸入 
 若干對字符串,每對字符串占一行并用一個(gè)空格分開。前一個(gè)字符串為母串,后者為子串。字符串只包含英文字母的大小寫。每個(gè)字符串不超過98個(gè)字符。
輸出 
 輸出子串在母串中首次出現(xiàn)的位置,如果母串中不包含子串則輸出0。每個(gè)整數(shù)占一行。
樣例輸入 
 ACMCLUB ACM 
 DataStructure data 
 domybest my 
 樣例輸出 
 1 
 0 
 3
未完 待續(xù)。。。。。。
#include<stdio.h> #include<stdlib.h> #include<string.h> #define N 100 #define ERROR 0 #define OK 1 #define MAX 100typedef struct{char *ch;int length; }String;int StrLength(String *s) {return s->length ; }int StrCompare(String *S,String *T) {int i = 0;while(S->ch[i]!='\0'&&T->ch[i]!='\0'){if(S->ch[i]!=T->ch[i])return -1;i++;}return 0; }int SubString(String *S,String *Sub,int len,int pos) {//用Sub返回串S的第pos個(gè)字符起長度為len的子串 int i = 0;if(pos<0||pos > S->length +1||len< 0||len>S->length)return ERROR;if(Sub->ch)free(Sub->ch);//釋放舊空間 if(!len){Sub->ch = NULL;//空子串 Sub->length = 0;}else{//完整子串 Sub->ch = (char*)malloc(len*sizeof(char));pos-=1;while(i < len){Sub->ch[i++] = S->ch[pos++];}if(S->ch[pos-1]!='\0')Sub->ch[i] = '\0';Sub->length = len;}return OK; }int Index(String *S,String *T,int pos) {//T為非空串。若主串S中第pos個(gè)字符之后存在與T相等的子串//則返回第一個(gè)這樣的子串在S中的位置,否則返回-1 int i = pos;int m,n;String sub;n = StrLength(S);m = StrLength(T);while( i <= n-m+1){SubString(S,&sub,m,i);if(StrCompare(&sub,T)!=0){i++;}elsereturn i;//返回子串在主串中的位置 }return -1;//S中不存在與T相等的子串 }int main() {String S,T;int dex,i,l1,l2;char str1[MAX+10],str2[MAX+10];while(scanf("%s",str1)!=EOF){memset(str2,0,sizeof(str2));scanf("%s",str2);l1 = strlen(str1);l2 = strlen(str2);S.ch = (char*)malloc(l1*sizeof(char));T.ch = (char*)malloc(l2*sizeof(char));S.ch = str1;T.ch = str2;S.length = l1;T.length = l2;dex = 1;i = Index(&S,&T,dex);if(i!= -1)printf("%d\n",i);elseprintf("ERROR\n");}return 0;}轉(zhuǎn)載于:https://www.cnblogs.com/hellocheng/p/7350134.html
總結(jié)
以上是生活随笔為你收集整理的HNCU 1746: 算法4-1,4-3:定位子串的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: [转] 深入浅出 妙用Javascrip
- 下一篇: java 基本数据类型及自己主动类型提升
