串的基本操作
# include <stdlib.h>
# include <iostream>
# include <stdio.h>
# define MaxSize 255 typedef struct { char ch[ MaxSize] ; int length;
} SString;
SString InitStr ( SString & S) { S. length= 0 ; return S;
}
SString SetStr ( SString & S) { char c; int i= 1 ; scanf ( "%c" , & c) ; while ( c!= '\n' ) { S. ch[ i++ ] = c; S. length++ ; scanf ( "%c" , & c) ; } return S;
}
int StrLength ( SString & S) { return S. length;
}
void ClearStrinf ( SString & S) { S. length= 0 ;
}
bool SubString ( SString & Sub, SString & S, int pos, int len) { if ( pos+ len- 1 > S. length) return false; for ( int i= pos; i< pos+ len; i++ ) { Sub. ch[ i- pos+ 1 ] = S. ch[ i] ; } Sub. length = len; return true;
}
bool StrCompare ( SString & S, SString & T) { for ( int i= 1 ; i<= S. length && i<= T. length; i++ ) { if ( S. ch[ i] != T. ch[ i] ) return S. ch[ i] - T. ch[ i] ; } return S. length- T. length;
}
int Index ( SString & S, SString & T) { int i= 0 ; int n= StrLength ( S) ; int m= StrLength ( T) ; SString Sub; while ( i<= n- m+ 1 ) { SubString ( Sub, S, i, m) ; if ( StrCompare ( Sub, T) != 0 ) i++ ; else return i; } return 0 ;
}
void ShowString ( SString & S) { for ( int i= 1 ; i< S. length; i++ ) { printf ( "%c" , S. ch[ i] ) ; } printf ( "\n" ) ;
} int main ( ) { printf ( "设置串:" ) ; SString S; InitStr ( S) ; SetStr ( S) ; int len1; len1= StrLength ( S) ; printf ( "串长度为:%d\n" , len1) ; printf ( "设置字串:" ) ; SString D; InitStr ( D) ; SetStr ( D) ; int len2; len2= StrLength ( D) ; printf ( "子串长度为:%d\n" , len2) ; printf ( "\n" ) ; printf ( "-----------求字符串的字串-------------\n" ) ; SString Sub; int pos, len; printf ( "输入截取的起始位置和长度:" ) ; scanf ( "%d,%d" , & pos, & len) ; if ( SubString ( Sub, S, pos, len) ) { printf ( "截取后的字串\n" ) ; ShowString ( Sub) ; } else printf ( "截取失败\n" ) ; printf ( "\n" ) ; printf ( "-------------定位字串-------------\n" ) ; int i; i= Index ( S, D) ; if ( i) printf ( "字串定位:%d" , i) ; else printf ( "字串定位失败\n" ) ; return 0 ;
}
展示