C remove the first character of the array

I have a line:

str1 = "abcabcabc"; 

How to delete the first character? I would like the end result:

 str1 = "bcabcabc"; 
+6
source share
6 answers

If you have a pointer to a string, for example:

 char *s = "This is my string"; 

then you can just do s++ .

If you have an array of characters, a pointer to that array might be a better option:

 char s[] = "This is my string"; char *ps = s; 

then you can do ps++ and make sure you are using ps , not s .

If you do not want to have a separate pointer to your array, you can use memmove to copy data:

 memmove (s, s+1, strlen (s+1) + 1); // or just strlen (s) 

although none of them will work for an initially empty string, so you need to check this first. Also keep in mind that trying to modify string literals this way (or in any way, really) is not recommended, as it is undefined as to whether it is allowed.

Another solution is just loop code:

 for (char *ps = s; *ps != '\0'; ps++) *ps = *(ps+1); *ps = '\0'; 

This will work for all rows, empty or others.

+18
source

Try:

 char str1[] = "abcabcabc"; char *pstr1; pstr1 = &(str1[1]); 

Bad practice, but since it is reserved on the stack, it should not kill you. Now, if you showed us your code ...


You can use strcpy :

 char str1[] = "abcabcabc"; char str2[sizeof(str1)-1]; if(strlen(str1) > 0) { strcpy(str2, &(str1[1])); } else { strcpy(str2, str1); } // str2 = "bcabcabc"; 

For C ++, you simply use std :: string :: substr :

 std::string str1 = "abcabcabc"; std::string str2 = str1.substr(1, str1.length() - 1); // str2 = "bcabcabc"; 
+4
source

Here is one way to do this:

 int index = 0; //index to cull memmove( &word[ index ] , &word[ index +1], strlen( word ) - index) ; 
+1
source

If you really wanted to say

 char str1 [] = "abcabcabc"; 

Then the easiest:

 str1 = &str1[1]; 

If you want to change the actual data, you just need to move everything one position. You can use a loop or memmove() for this. The recursive function is redundant.

If you really meant C ++, and you are using a string object, you can use

 str1 = str1.substr(1); 
0
source

Well, as far as I know, if you are worried about memory allocation, you need to copy (str1 + 1) to a new line for which you will personally allocate memory, and then free the first pointer. The easiest way to do this is to simply increase str1 with str1 ++; This will point one character further than before, and give the desired result with just a line of code.

0
source
 #include <stdio.h> #include <conio.h> main(){ char a[10]; int i; gets(a); for (i = 0; a[i] != '\0'; i++) { a[i] = a[i + 1]; } printf("\n"); puts(a); getch(); } 
0
source

Source: https://habr.com/ru/post/886207/


All Articles