简体   繁体   中英

Getting substring from string in C

I have a string "abcdefg-this-is-a-test" and I want to delete the first 6 characters of the string. This is what I am trying:

char contentSave2[180] = "abcdefg-this-is-a-test";
strncpy(contentSave2, contentSave2+8, 4);

No luck so far, processor gets stuck and resets itself. Any help will be appreaciated.

Question: How can I trim down a string in C?

////EDIT//// I also tried this:

memcpy(contentSave2, &contentSave2[6], 10);

Doesn't work, same problem.

int len=strlen(content2save);
for(i=6;i<len;i++)
   content2save[i-6]=content2save[i];

content2save[i-6]='\0'

This will delete first 6 charcters . Based on requirement you may modify your code. If you want to use an inbuilt function try memmove

The problem with your first code snippet is that it copies the middle four characters to the beginning of the string, and then stops.

Unfortunately, you cannot expand it to cover the entire string, because in that case the source and output buffers would overlap, causing UB:

If the strings overlap, the behavior is undefined.

Overlapping buffers is the problem with your second attempt: memcpy does not allow overlapping buffers, so the behavior is undefined.

If all you need is to remove characters at the beginning of the string, you do not need to copy it at all: simply take the address of the initial character, and use it as your new string:

char *strWithoutPrefix = &contentSave2[8];

For copying of strings from one buffer to another use memcpy :

char middle[5];
memcpy(middle, &contentSave2[8], 4);
middle[4] = '\0'; // "this"

For copying potentially overlapping buffers use memmove :

char contentSave2[180] = "abcdefg-this-is-a-test";
printf("%s\n", contentSave2);
memmove(contentSave2, contentSave2+8, strlen(contentSave2)-8+1);
printf("%s\n", contentSave2);

Demo.

Simply you can use pointer because contentSave2 here is also a pointer to a char array plus this will be quick and short.

char* ptr = contentSave2 + 6;

ptr[0] will be equal to contentSave2[6]

You can use memmove function.

It is specially used when source and destination memory addresses overlap.

Small word of advice, try to avoid copying to and from overlapping source and destination. It is simply a buggen.

The following snippet should works fine:

#include <stdio.h>
#include <string.h>

int main() {
    char contentSave2[180] = "abcdefg-this-is-a-test";
    strncpy(contentSave2, contentSave2+8, 4);
    printf("%s\n", contentSave2);
    return 0;
}

I would suggest posting the rest of your code because your issue is elsewhere. As others pointed out, watch out for overlap when you use strncpy though in this specific case it should works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM