remove function in a char string

What function can i use to remove characters from a char string starting with the a given index?
Last edited on
Between this https://www.cplusplus.com/reference/string/string/
and this https://www.cplusplus.com/forum/general/274406/
you should be able to figure something out.

Certainly, you need to make an attempt before posting a 1-line gimme.
dude i didnt'd asked for the program, i asked what function i could use
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
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
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
memmove will do this as a one liner; be sure to include the zero termination letter in the move index.
Last edited on
Topic archived. No new replies allowed.