1

For example, in python, you can index strings like this

some_string = "hello"
substring = some_string[0:3]

and substring will be "hel"

however, in C, if I have

char some_string[] = {'h', 'e', 'l', 'l', 'o'};

Is there a way to get just

{'h', 'e', 'l'}

There is probably a very simple solution that I am overlooking, but I find it hard to think in two languages sometimes.

1
  • 3
    Note that your some_string is not a C string. It lacks the null-terminator. Commented Oct 21, 2019 at 16:40

2 Answers 2

3

Not very simple, primarily because of memory management. You either need substring to be an array of sufficiently many characters, or need to allocate the memory dynamically. for example:

char *some_string = "hello";
char substring[4];
strncpy(substring,some_string,3);
substring[3]='\0';

or:

char *substring(char *s, int start, int len)
{
    char *s2= malloc(len+1);
    strncpy(s2, s+start, len);
    s2[len]='\0';
    return s2;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Note: you'll need to check for start <= strlen(s)), too. (plus: strncpy() makes no sense here. (it seldom does))
@wildplasser, suggestions for alternative to strncpy?
Maybe just strcpy() or even memcpy() ?
@wildplasser, strcpy() won't do because not till end-of-string may need to be copied. memcpy() could do. What is wrong with strncpy()?
2

For starters this declaration of a character array

char some_string[] = {'h', 'e', 'l', 'l', 'o'};

does not contain a string.

You should write either

char some_string[] = {'h', 'e', 'l', 'l', 'o', '\0'};

or

char some_string[] = {"hello"};

or

char some_string[] = "hello";

The only way to get a substring is to copy the sub-range of characters in another character array.

for example

#include <string.h>

// ...

char substring[4];

strncpy( substring, some_string, 3 );
substring[3] = '\0';

3 Comments

I would consider using memcpy rather than strncpy here.
@ChristianGibbons In general a copied string can be less than the requested range.
That is true in a general case, but I got the impression that we were dealing with a scenario in which we knew the substring to be copied was full-length. Especially considering the OP is looking for it to be equivalent to giving a range in a python string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.