You are on page 1of 6

Write a program to implement the string

operations - insertion, deletion and replacement.

Insertation:
#include<stdio.h>
int insertSorted(int arr[], int n,
int key,
int capacity)
{
if (n >= capacity)
return n;

arr[n] = key;

return (n + 1);
}
int main()
{
int arr[20] = {10, 12, 14, 16, 18, 20};
int capacity = sizeof(arr) / sizeof(arr[0]);
int n = 6;
int i, key = 22;
printf("\n Before Insertion: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
n = insertSorted(arr, n, key, capacity);
printf("\n After Insertion: ");
for (i = 0; i < n; i++)
printf("%d ",arr[i]);
printf("\n");

return 0;

}Output:

Delete:
#include<stdio.h>
int findElement(int arr[], int n,
int key);
int deleteElement(int arr[], int n,
int key)
{
int pos = findElement(arr, n, key);

if (pos == - 1)
{
printf("Element not found");
return n;
}
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];

return n - 1;
}
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;

return - 1;
}
int main()
{
int i;
int arr[] = {100, 200, 300, 400, 500};

int n = sizeof(arr) / sizeof(arr[0]);


int key = 300;

printf("Array before deletion\n");


for (i = 0; i < n; i++)
printf("%d ", arr[i]);

n = deleteElement(arr, n, key);

printf("\nArray after deletion\n");


for (i = 0; i < n; i++)
printf("%d ", arr[i]);

return 0;

}Output:

Replacement:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* replaceWord(const char* s, const char* oldW,
const char* newW)
{
char* result;
int i, cnt = 0;
int newWlen = strlen(newW);
int oldWlen = strlen(oldW);

for (i = 0; s[i] != '\0'; i++) {


if (strstr(&s[i], oldW) == &s[i]) {
cnt++;

i += oldWlen - 1;
}
}
result = (char*)malloc(i + cnt * (newWlen - oldWlen) + 1);

i = 0;
while (*s) {

if (strstr(s, oldW) == s) {
strcpy(&result[i], newW);
i += newWlen;
s += oldWlen;
}
else
result[i++] = *s++;
}

result[i] = '\0';
return result;
}
int main()
{
char str[] = "Hello Anzum";
char c[] = "A";
char d[] = "T";

char* result = NULL;

printf("Old string: %s\n", str);

result = replaceWord(str, c, d);


printf("New String: %s\n", result);

free(result);
return 0;
}

Output:

You might also like