Dec 1, 2020 at 7:30am UTC
What function can i use to remove characters from a char string starting with the a given index?
Last edited on Dec 1, 2020 at 7:35am UTC
Dec 1, 2020 at 9:05am UTC
dude i didnt'd asked for the program, i asked what function i could use
Dec 1, 2020 at 9:31am UTC
dude i didnt'd asked for the program, i asked what function i could use
Do you know how to get upper case on your keyboard, or what the difference between tenses is?
Anyway, try the first reference that @salem c gave you if you want std::string, or write some code for us to debug if you insist on c-strings.
If you use std::string then consult
https://www.cplusplus.com/reference/string/string/erase/
Last edited on Dec 1, 2020 at 10:21am UTC
Dec 1, 2020 at 10:15am UTC
There is no function that can do this. You have to write your own.
Maybe sth. like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <stdio.h>
#include <string.h>
void remove_char(const char *src, char *dest, char ch, int index)
{
int j = 0, i = 0;
for (i = 0; i <= index; ++i)
{
dest[i] = src[i];
}
j = i;
for (;src[i] != '\0' ; ++i)
{
if (src[i] != ch)
{
dest[j] = src[i];
++j;
}
}
dest[j] = '\0' ;
}
int main()
{
char src[20] = "Hello world!" ;
char dest[20] = {0};
printf("Original string: %s\n" , src);
remove_char(src, dest, 'l' , 5);
printf("Modified string: %s\n" , dest);
}
Last edited on Dec 1, 2020 at 10:16am UTC
Dec 1, 2020 at 11:04am UTC
to remove characters from a char string starting with the a given index
Do you mean a c-style null terminated string or a C++ std::string? Do you mean remove a specified number of chars starting at the given index or specified chars starting at the given index???
If std::string, use .erase()
http://www.cplusplus.com/reference/string/string/erase/
If c-style null-terminated, then to remove specified number of chars or specified char, consider:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include <stdio.h>
void remove_char(char * src, size_t index, size_t nochrs = 1)
{
for (src += index + nochrs; *src; ++src)
*(src - nochrs) = *src;
*(src - nochrs) = 0;
}
void remove_charc(char * src, char ch, size_t index)
{
for (src += index; *src; )
if (*src == ch)
remove_char(src, 0, 1);
else
++src;
}
int main()
{
char src[20] = "Hello world!" ;
printf("Original string: %s\n" , src);
remove_char(src, 6, 3);
printf("Modified string: %s\n" , src);
remove_charc(src, 'l' , 2);
printf("Modified string: %s\n" , src);
}
Original string: Hello world!
Modified string: Hello ld!
Modified string: Heo d!
Last edited on Dec 1, 2020 at 11:20am UTC
Dec 2, 2020 at 4:23am UTC
memmove will do this as a one liner; be sure to include the zero termination letter in the move index.
Last edited on Dec 2, 2020 at 4:24am UTC