⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 substr.c

📁 提供大量C代码来实现不同功能
💻 C
字号:
/* function to get the length of a string */
int length(string)
char string[ ] ;
{
    int index = 0 ;

    while (string[index] != '\0' )
        index ++ ;
    return (index);
}

/*    function to find the position of string2 in string1 */
int find_string(string1,string2)
char string1[ ] ,string2[ ] ;
{
    char temp;
    int index1=0 , index2 ;

    while ( string1[index1] != '\0' )
    {
        index2 = 0 ;
	temp=string1[index1+index2];
        while ( (string2[index2] != '\0' ) &&
	      (temp == string2[index2] ) )
	{
	    temp = string1[index1+ ++index2];
	}

        if ( string2[index2] == '\0' )  /* found */
            return (index1) ;

        index1 ++ ;
    }
    /* not found */
    return (-1) ;
}

/*
    function to remove the substring from source_string
*/
remove_string(string,start,count)
char string[ ] ;
int start,count;
{
    int len,index;
    char temp;

    index = start + count ;
    len = length(string) ;
    while ( len >index )
    {
        temp = string[index];
	string[index-count]=temp;
        index ++ ;
    }
    string[index-count] = '\0' ;
}


/*
    function to insert a string into another one
*/
insert_string(string1,string2,pos)
char string1[],string2[];
int pos;
{
    int len1,len2,index;
    char temp;

    len1 = length(string1);
    len2 = length(string2);
    index = len1 ;

    while ( index >= pos )
    {
	temp = string1[index];
        string1[index+len2] = temp;
        index -- ;
    }

    index = 0;
    while ( index < len2 )
    {
	temp = string2[index];
        string1[pos+index] = temp;
        index ++;
    }
}


/*
    function to  replace string1 with string2  in source
*/
int replace(source,string1,string2)
char source[],string1[],string2[];
{
    int start,count;

    if ( (start=find_string(source,string1)) != -1 )
    {
        count = length( string1 );
        remove_string(source,start,count) ;
        replace (source,string1,string2);
        insert_string(source,string2,start);
        return ( 1 );
    }
    return ( 0 );
}

main ( )
{
    char source[80],string1[80],string2[80];

    printf("Source_string :\n");
    scanf ("%s",source);
    printf("String1 :\n");
    scanf ("%s",string1);
    printf("String2 :\n");
    scanf ("%s",string2);

    if ( replace(source,string1,string2) )
        printf("\n%s\n",source);
    else printf("\n Not changed.\n");
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -