user1798862
user1798862

Reputation: 55

How to obtain substring from full string?

I have to try and use the GetSubstring function to print the result so that

printf(GetSubstring("character", 4, 3, resultArray));

outputs act

Limitations: can't call other functions or macros, can't add any other variables, can't set variable to 0. Can only change function GetSubstring.

Here is my current code.

#include <stdio.h>
#include <stdlib.h>
char *GetSubstring(const char source[], int start, int count, char result[]);

int main(void)
{
const char source[] = "one two three";
char result[] = "123456789012345678";

puts(GetSubstring("character", 4, 3, result));

return(EXIT_SUCCESS);
}


char *GetSubstring(const char source[], int start, int count, char result[])
{
    char *copy = result;
    for (; *source != '\0' || *source == source[start]; start--)
    {
        while (*source != '\0')
        {
        *result++ = *source++;
        }

    }

    *result = '\0';
    return (copy);                                      // outputs character
    // return (result);                                 // outputs 012345678
}

Thank you for your help.

Upvotes: 0

Views: 284

Answers (3)

Miles
Miles

Reputation: 189

Here is my solution.

  1. Make space on heap for your substring

  2. Iterate through source until you hit the end of the string or you finish copying. Copy characters to substring you want to return

  3. Add the terminating character

  4. Return the result

Hope this helps

char *GetSubstring(const char source[], int start, int count, char result[])
{
    int i = 0;
    char *substr = (char *) malloc(sizeof(char));
    for (; source[start] != '\0' && count > 0; count--)
    {
        substr[i++] = source[start++];
    }

    substr[i] = '\0';
    return (substr);                                   
}

Upvotes: 0

paddy
paddy

Reputation: 63461

This line is supposed to terminate the string:

*result += '\0'

But it doesn't because you are adding zero to the existing value. Try setting it to zero instead:

*result = '\0'

More importantly, your loop is wack. This contains a whole lot of recipes for trouble:

for (; *source != '\0' || *source == source[start]; start--)
{
    while (*source != '\0')
    {
        *result++ = *source++;
    }
}

Why don't you begin at start, and then increment...

int i = 0;
const char *str = &source[start];

while( i < count && *str != '\0' ) {
    result[i++] = *str++;
}
result[i] = '\0';

Upvotes: 2

Aniket Inge
Aniket Inge

Reputation: 25695

The error seems to be here: result += '\0'. which should be *result = '\0';

Upvotes: 0

Related Questions