Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using C write a function, halfstring, which creates a new string which skips eve

ID: 3747095 • Letter: U

Question

Using C write a function, halfstring, which creates a new string which skips every second characters of the first string.

For example: "John Smith" would become "Jh mt"

The function prototype must be:

void halfstring(const char [ ], char [ ]);

Think how you will use the two parameters.

As a result, you will have both the resulted string and the original one.

Do not use ANY system-defined string functions (i.e. those found in the string.h library including but not limited to strlen, strcat, and strcpy.).

Write driver code to test your function.

As we discussed in the class, your program and output must be self-explanatory.

Explanation / Answer

#include<stdio.h>

#include<string.h>

// ans is the string where the resultant string will be stored

void halfstring(const char str[], char ans[])

{

    int len = 0;

   

    // point ptr to first character of str

    char *ptr = (char *)str;

   

    // point to first character of ans

    char *ans_ptr = ans;

   

    for( ; *ptr != '' ; )

    {

        // copy the character to the location pointed by ans_ptr

        *ans_ptr = *ptr;

       

        ans_ptr++;

       

        // increment the pointer to next character

        ptr++;

      

        // if the string is not ended

        if( ptr != NULL && ptr != '' )

            ptr++;

    }

   

    // add the ending character to ans

    *ans_ptr = '';

}

int main()

{

    const char str[] = "John Smith";

   

    char ans[ strlen(str) ];

   

    halfstring( str , ans );

   

    printf("Resultant String : %s" , ans);

}

Sample output

Resultant String : Jh mt

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote