This question requires the implementation of a function that, for a given string and two characters, prints out all the characters in the given string starting from the position matching the first character to the position matching the second character.

This question requires the implementation of a function that, for a given string and two characters, prints out all the characters in the given string starting from the position matching the first character to the position matching the second character.

Function interface definition:

 
 

char *match( char *s, char ch1, char ch2 );

The function matchshould print all characters sfrom ch1to ch2and return ch1the address.

Sample Referee Test Procedure:

 
 

#include <stdio.h> #define MAXS 10 char *match( char *s, char ch1, char ch2 ); int main() { char str[MAXS], ch_start, ch_end, *p; scanf("%s\n", str); scanf("%c %c", &ch_start, &ch_end); p = match(str, ch_start, ch_end); printf("%s\n", p); return 0; } /* 你的代码将被嵌在这里 */

Input example 1:

program
r g

Output sample 1:

rog
rogram

Input example 2:

program
z o

Output sample 2:

(空行)
(空行)

Input example 3:

program
g z

Output sample 3:

gram
gram

 

char *match( char *s, char ch1, char ch2 )
{
    //定义变量存储找到时的地址方便返回
    char* ret;

    //先查找ch1
	while(*s!=ch1&&*s!='\0')
    {
        s++;
    }

    //如果没有找到就不会继续去查找ch2,如果找到接下来查找ch2
    if(*s!='\0')
    {
        //记录地址
        ret=s;
        //查找ch2
        while(1)
        {
            if(*s=='\0')
            {
                break;
            }
            printf("%c",*s);
            if(*s==ch2)
            {
                break;
            }
            
            s++;
        }
        
      
    }
    printf("\n"); 
    return ret;
}

Guess you like

Origin blog.csdn.net/qq_61903414/article/details/124077466