Getting substring from another string up to a certain point

Hello, in my program I have this function:
1
2
3
4
5
6
7
8
9
10
11
const char * get_substring_until_point(const char * s_stringToSearch, int i_endPoint)
{
    const char * s_tempString = "foo";
    char * s_NONSTATICtempString = (char *)s_tempString;
    for(int i = 0; i < i_endPoint; i ++)
    {
        s_NONSTATICtempString[i] = s_stringToSearch[i];
    }
    s_tempString = (const char *) s_NONSTATICtempString;
    return s_tempString;
}

What I want it to do is return part of a string up to a certain point, for example, get_substring_until_point("Hello there", 5) would return "Hello". I have tried re-arranging this code a number of ways but I keep getting run-time error(s). The reason for all the casting in the code is because when I use non constant chars for strings, I get depreciated conversion warnings and then more run-time errors. I have the feeling that I am doing something disatrously wrong, does anybody know how I should be going about this?

Thankyou.
Reserve space before filling it with chars

1
2
3
4
5
6
7
8
9
10
char * get_substring_until_point(const char * s_stringToSearch, int i_endPoint)
{
    char * s_tempString = new char[i_endPoint + 1];
    for(int i = 0; i < (i_endPoint) && (s_stringToStretch[i] != NULL); i ++)
    {
        s_tempString[i] = s_stringToSearch[i];
    }
    s_tempString[i_endPoint] = NULL; //terminate string with a NULL
    return s_tempString;
}


Does this help? notice the other condition in the for loop, to make sure that you don't hit the end of the passed string incase the passed length is longer than the string.

Make sure you delete your new returned string after you're done with it, for correct memory management.
Last edited on
Thankyou for that :) Its working now :)
Topic archived. No new replies allowed.