String inserting/deleting are similar to integer array shifting, because strings are arrays of char.

This time, we will insert or delete more than one charactes.

/*Description:  String Processing
		insert, delete
		
Author:  Liutong Xu
*/

#include<stdio.h>
#define LSIZE 81

void strInsert(char str1[LSIZE], int pos, char str2[LSIZE]);
void strDelete(char str1[LSIZE], int iBegin, int iLen);
int main()
{
	char str1[LSIZE] = "Welcome Beijing!";
	char str2[] = "to ";
	int iBegin, iLen;
	int pos = 8;
	iBegin = 5;
	iLen = 6;

	printf("string1 is %s\n", str1);
	strInsert(str1, pos, str2);
	printf("\nafter inserting str2 at position %d\n", pos);
	printf("string1 is %s\n", str1);	
	
	strDelete(str1, iBegin, iLen);
	printf("\nafter deleting %d char from position %d\n", iLen, iBegin);
	printf("string1 is %s\n", str1);	
	
	return 0;
} 

void strDelete(char str[LSIZE], int iBegin, int iLen)	//delete iLen chars from str[iBegin] 
{
	int i;
	int len = 0;
	while(str[len]) len++;
	
	if(len > iBegin + iLen)			//NOTE
		for(i = iBegin; i<=len-iLen; i++)
			str[i] = str[i + iLen];
	else 
		str[iBegin] = '\0';
}

void strInsert(char str1[LSIZE],int pos,char str2[LSIZE])	//insert str2 at str1[pos]
{
	int i, i1 = 0, i2 = 0;

	while(str2[i2]) i2++;	//length of str2;
	
	while(str1[i1]) i1++;	//str1[i1] is '\0'
	
	for(i = i1; i >= pos; i--)
		str1[i+i2] = str1[i];//move str1[pos-i1] to a right offset i2 
	
	for(i = 0; i < i2; i++)		//insert str2
		str1[pos + i] = str2[i];
}

stdout

string1 is Welcome Beijing!

after inserting str2
string1 is Welcome to Beijing!

after deleting 6 char from position 5
string1 is WelcoBeijing!

end

You have no rights to post comments