8

I have a string and I want its sub string from 5th location to last location. Which function should I use?

7 Answers 7

9

You can use the memcpy() function which is in string.h header file.

memcpy() copies bytes of data between memory blocks, sometimes called buffers. This function doesn't care about the type of data being copied--it simply makes an exact byte-for-byte copy. The function prototype is

void *memcpy(void *dest, void *src, size_t count);

The arguments dest and src point to the destination and source memory blocks, respectively. count specifies the number of bytes to be copied. The return value is dest.

If the two blocks of memory overlap, the function might not operate properly -- some of the data in src might be overwritten before being copied. Use the memmove() function, discussed next, to handle overlapping memory blocks. memcpy() will be demonstrated in program below.

You can also find an example for these function over here: http://www.java-samples.com/showtutorial.php?tutorialid=591

Sign up to request clarification or add additional context in comments.

Comments

6

If you won't be using the original string for anything else, you can just use &s[4] directly. If you need a copy, do

char new_str[STR_SIZE + 1] = {0};
strncpy(new_str, &s[4], STR_SIZE);

1 Comment

strncpy(), despite its name, was designed to work with unterminated character arrays. Your code may leave new_str without a '\0'. Add new_str[STR_SIZE] = 0 or make sure you have enough space and use strcpy().
4
void substr(char *s, int a, int b, char *t) 
{
    strncpy(t, s+a, b);
}

Most simple solution yet efficient. Declare some t char variable to hold the outcome, then just pass s as the string to manipulate, a as the initial offset and b as the length of the string you want to extract.

char t[255]="";
substr(s, a, b, t);

Comments

4

Instead of telling you how to extract a substring (which other answers have already done), I'm going to explain why C does not have a standard substring function.

If C did have a substring function, its declaration might look something like this:

char *substr(const char *instring, size_t pos, size_t len);

This would take the input string instring, extract the substring of length len starting at position pos, and return it as a new string.

But the $64,000 question is, how would it return the new string?

It could dynamically allocate space for the new string, but C's utility functions typically never do that. (The only exception that pops to mind is strdup, and it's not even a standard C function.)

It could insert a '\0' charater into instring and then return a pointer into instring, but that would obviously modify instring, which a function like this shouldn't do. (Indeed that's why I've speculated that the hypothetical substr function here would accept a const char * pointer.)

So it turns out that, in C, it's actually impossible to write a proper "utility" substring function, that doesn't do any dynamic memory allocation, and that doesn't modify the original string.

All of this is a consequence of the fact that C does not have a first-class string type.

It's properly the caller's decision whether or not it's acceptable to modify the original string. It's properly the caller's decision how to allocate memory for the extracted substring. So there's hardly anything left for the hypothetical substr function to do. It's just some pointer arithmetic, and it might be nice to encapsulate it in a "substr" function, but it doesn't really end up saving the caller any work, so the caller might as well do the pointer arithmetic itself, after deciding how it wants to handle those harder problems.

If the caller's comfortable modifying the original string, it's straightforward to do that:

char instring[] = "marshmallow";
int pos = 3, len = 5;
instring[pos + len] = '\0';
char *substr = &instring[pos];
printf("%s\n", substr;

If the caller wants to allocate separate memory, either as an array or by calling malloc, that's also pretty straightforward:

char *substr = malloc(len + 1);
strncpy(substr, &instring[pos], len);
substr[len] = '0';

So if C had a first-class string type, it would certainly have a substr function in its standard library -- but since it doesn't, it doesn't. (C++, by contrast, does have a first-clss string type, and it has a substr method to go with it.)

Comments

2

If you know the character also in the string from where you want to get the substring then you can use strstr function. It locates the substring. But if u do not know the character from where you want to retrieve then you can use the strcpy or strncpy to get the string as Eric has mentioned.

Comments

1

s+4

This provides the sub-string, as requested in the question, not a copy of the sub-string. 's+4' returns the sub-string at the 5th position of string 's'. This is an efficient primitive operation in C and does not use any function calls.

If the application requires making a local copy of the result, e.g. if the result will be modified:

    char substring[strlen(s)-3] ;
    strcpy(substring, s+4) ;

Note that this requires a modern C compiler that allows variable sized arrays. For a non-local copy, use malloc to allocate the substring (e.g. char *substring = (char *)malloc(strlen(s)-3) ;), which works on any C compiler.

Comments

0

If I understand correctly you need to use some delimiter, in order to break up the string in substrings. For example "one#two#three" broken up in one two three. If so:

#include <stdio.h>
#include <string.h>
int main()
{
    char test[] = "one#two#three";
    char* res;
    res = strtok(test, "#");
    while(res) {
        printf("%s\n", res);
        res = strtok(NULL, "#");
    }

    return 0;
}

You call strtok() once with the string you want to tokenize. Each of the following calls should pass NULL, in order to continue with the string from the first call. Also note that strtok may modify the original pointer, so if it is dynamically allocated you should save it before passing it to strtok.

2 Comments

I don't have any delimiter and also I don't want to write any extra codes as it would be considered redundancy. I want to use any library function.
strtok() is library function, but I misunderstood your question so my post is irrelevant. Sorry.

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.