в настоящее время я могу удалить один символ из строки, но я не могу понять, как настроить «символ», чтобы он мог удалить несколько символов ... какие-либо предложения?
#include <string.h>
void remove_character(char *string, char *remove);
int main(void){
char s[] = "Thi!s is s!ome tex!t that we'!ll check for plagiarism";
char symbol[] = "!";
printf("%s\n", s);
remove_character(s, symbol);
printf("%s\n", s);
return(0);
}
void remove_character(char *string, char *remove){
int position = 0;
while (string[position] != '\0')
{
if (string[position] == *remove){
int newposition = position;
while (string[newposition] != '\0')
{
string[newposition] = string[newposition+1];
newposition++;
}
} else position++;
}
}





Если вы можете удалить 1, просто зациклите функцию для массивов съемных символов.
void remove_character(char *string, char remove){
int position = 0;
while (string[position] != '\0')
{
if (string[position] == remove){
int newposition = position;
while (string[newposition] != '\0')
{
string[newposition] = string[newposition+1];
newposition++;
}
} else position++;
}
}
void remove_character(char *string, char *remove){
for(each char in remove){
remove_character(string, remove[index])
}
Вам не нужно «сжимать» строку каждый раз, когда функция встречает удаляемый символ.
#include <stdio.h>
#include <string.h>
// Define the function ahead of its use. It is its own prototype.
void remove_character( char *str, char *remove ) {
// copy characters, but only increment destination for "non-remove" characters.
for( size_t src = 0, dst = 0; ( str[dst] = str[src] ) != '\0'; src++ )
dst += (strchr( remove, str[dst] ) == NULL);
}
int main( void ) {
char s[] = "Thi!s is s!ome tex!t that we'!ll check for plagiarism";
char symbols[] = "!s"; // Stripping out '!' and 's'
puts( s ); // simpler
remove_character( s, symbols );
puts( s ); // simpler
return 0; // return is NOT a function call. No '()'.
}
Thi!s is s!ome tex!t that we'!ll check for plagiarism
Thi i ome text that we'll check for plagiarim
src и dst - это просто две индексные переменные... "от источника к месту назначения"... Источник увеличивается до конца строки. Назначение увеличивается только тогда, когда символ должен быть сохранен (возможно, перезапись скопированного символа, который должен быть удален). Всего два индекса...
Вам нужно скопировать всю оставшуюся часть строки, иначе вы только замените один символ другим, используйте memmove.
#include <string.h>
#include <stdio.h>
void main(void)
{
char String[] = { "Hello" };
char Remove = 'l';
char* pSearch = String;
while (*pSearch) // is not 0
{
if (*pSearch == Remove)
memmove(pSearch, pSearch + 1, strlen(pSearch) + 1);
else
pSearch++;
}
printf("%s\n", String);
}
Спасибо, это работает, но можете ли вы объяснить, что означают «src» и «dst», если они что-то значат ?? Такого еще не видел :)