Reputation:
I've my char array, that has maximum size 1024. Anyway it contains a string of 200 characters. I want to remove exactly the first 80 characters from this 200 characters string. How can I do it?
char my_array[1024];
for(int i = 80; i < sizeof(my_array); i+=1)
{
my_array[i-80] = my_array[i];
}
I tryed this, but it doesn't work. Do you know any solution to do this? Thank you everybody for your help!
Upvotes: 0
Views: 233
Reputation: 1
Instead of changing the array, you could, depending on your need, just create a pointer pointing to the 81th char
of the original string, this pointer now points to a string where 80 char
are removed. Here a shorter example with just 10 char
s removed.
int main(void)
{
char orig[]="This is a long string";
char *s=orig+10;
puts(s);
return 0;
}
This will print
long string
You said you want to remove characters. A char
is not the same as a character, which is not simple to define and hard to count. First, you have to know the encoding and the value of CHAR_BIT
. Most likely you will use UTF-8 and CHAR_BIT==8
. Counting code points is relatively easy, just count the char
s which indicate the beginning of a code point (Bit 7 is 0 or Bit 6 is set). But then it gets complicated. You need to be aware of combining characters which are code points that are combined with other code points to create a single character. Which is also harder because, depending on the context, a character can't be combined. Then you need to define how you count. For example, in Korean, multiple simple "characters" can be combined into a single "character" by placing them in a single square, how do you count them? (Disclamer i don't understand Korean and i don't really understand how Korean works.)
Counting character goes beyond this answer, i only want to show you that "removing 80 characters" isn't easy to define.
Upvotes: 0
Reputation: 310950
Use the standard C string function memmove
. For example
#include <string.h>
//...
memmove( my_array, my_array + 80, strlen( my_array ) - 79 );
The magic number 79
means that you need to copy all characters in the string except 80
characters but including the terminating zero character '\0'
.
You need to guarantee that the array indeed contains a string and that the stored string has length (strlen( my_array )
) not less than 80
characters.
For example
size_t n = strlen( my_array );
if ( !( 80 < n ) )
{
myarray[0] = '\0';
}
else
{
memmove( my_array, my_array + 80, n - 79 );
}
Here is a demonstrative program that removes first 7 characters from a string stored in a character array.
#include <string.h>
#include <stdio.h>
int main( void )
{
char s[] = "Hello World";
size_t n = 6;
puts( s );
memmove( s, s + n, strlen( s ) - n + 1 );
puts( s );
}
The program output is
Hello World
World
Upvotes: 2