删除字符串中指定位置字符
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_DATA_LENTH (20)
#define TRUE (0)
#define FALSE (-1)
#define MAX_CHAR_PER_LINE (5)
typedef struct Ostring_s{
unsigned char array[MAX_DATA_LENTH];
unsigned int integer;
}Ostring_t;
void Ostring_delete(Ostring_t *string, int i, int j)
{
int string_len = sizeof(Ostring_t);
int len1, len2, len3;
int k;
unsigned char *str1 = NULL;
unsigned char *str2 = NULL;
unsigned char *str3 = NULL;
/* 字符串分为三段 */
len1 = i-1;
len2 = j-i+1;
len3 = string_len-j;
/* 每一段的首地址 */
str1 = (unsigned char *)string;
str2 = str1+len1;
str3 = str2+len2;
printf("\r\nstring = 0x%x, str1 = 0x%x, str2 = 0x%x, str3 = 0x%x\r\n", string, str1, str2, str3);
/* 删除中间段字符 */
//memset(str2, 0, len2);
for(k=0; k<len2; k++)
{
*(str2+k) = 0;
}
/* 复制字符串使连续 */
//memcpy(str2, str3, len3);
for(k=0; k<len3; k++)
{
*(str2+k) = *(str3+k);
}
/* 删除尾部字符 */
//memset(str2+len3, 0, len2);
for(k=0; k<len2; k++)
{
*(str2+len3+k) = 0;
}
}
void String_print(unsigned char *string, int length)
{
int l;
for(l = 0; l<length; l++)
{
if(0 == (l%MAX_CHAR_PER_LINE))
{
printf("\r\n");
}
printf("0x%-5x ",*(string+l));
}
}
int main(void)
{
/* 初始化 */
Ostring_t *string;
int string_len = sizeof(Ostring_t);
string = (Ostring_t *)malloc(string_len);
memset(string, 0, sizeof(Ostring_t));
/* 赋值 */
memcpy(string->array, "abcdefghijklmnopq", sizeof("abcdefghijklmnopq"));
string->integer = 345;
/* 完整打印 */
printf("\r\nstring print before:\r\n");
String_print((unsigned char*)string, string_len);
/* 删除后打印 */
Ostring_delete(string, 2,8);
printf("\r\nstring printf after:\r\n");
String_print((unsigned char*)string, string_len);
free(string);
return TRUE;
}
好像是这么回事,晚点整理总结