با سلام
این سورس رو مشاهده کنید.
#include <stdio.h>
#include <string.h> // strncpy
#define MAX_STRING 1024
#define STR1 "Thisx isx ax testx"
#define STR2 "Hello xWorld!"
void delete_at(char *src, int pos, int len);
void delete_char(char *src, char c, int len);
int
main(void)
{
char buf1[MAX_STRING];
char buf2[MAX_STRING];
strncpy(buf1, STR1, sizeof(buf1));
strncpy(buf2, STR2, sizeof(buf2));
printf("\n");
printf("Delete all 'x' characters from: [%s] -> ", buf1);
delete_char(buf1, 'x', 0);
printf("[%s]\n\n", buf1);
printf("Delete the character at position 6 (zero offset) from: [%s] -> ", buf2);
delete_at(buf2, 6, 0);
printf("[%s]\n\n", buf2);
return 0;
}
// main()
/**
* Delete a character from the specified position (zero offset)
*
* The len parameter allows the function to work with non null terminated
* strings and could also be considered a weak attempt at buffer overflow
* protection.
*
* @note The original string is modified.
*
* @param[in] src Pointer to string from which to remove the character
* @param[in] pos Zero-offset position of the character to remove
* @param[in] len Max number of characters to process
*/
void
delete_at(char *src, int pos, int len)
{
char *dst;
int i;
if ( pos < 0 )
return;
// Small attempt to control a buffer overflow if the
// the string is not null-terminated and a proper length
// is not specified.
if ( len <= 0 )
len = MAX_STRING;
if ( pos >= len )
return;
src += pos;
dst = src;
src++;
for ( i = pos + 1 ; i < len && *src != 0 ; i++ )
*dst++ = *src++;
// Ensure the string is null-terminated.
*dst = 0;
return;
}
// delete_at()
/**
* Delete all occurrences of a character from a string
*
* The len parameter allows the function to work with non null terminated
* strings and could also be considered a weak attempt at buffer overflow
* protection.
*
* @note The original string is modified.
*
* @param[in] src Pointer to string from which to remove characters
* @param[in] c Character to remove
* @param[in] len Max number of characters to process
*/
void
delete_char(char *src, char c, int len)
{
char *dst;
int i;
// Do not remove NULL characters.
if ( c == 0 )
return;
// Small attempt to control a buffer overflow if the
// the string is not null-terminated and a proper length
// is not specified.
if ( len <= 0 )
len = MAX_STRING;
dst = src;
for ( i = 0 ; i < len && *src != 0 ; i++, src++ )
{
if ( *src != c )
*dst++ = *src;
}
// Ensure the string is null-terminated.
*dst = 0;
return;
}
// delete_char()