C string manipulation for removing xx:xx:xx:xx:xx:xx - c

I have a problem removing a substring xx:xx:xx:xx:xx:xx from one main string. Here is the background info for the problem:
in a function void funA():
void funA(const char* sth){
if (sth == THINGA){
// do A;
}
else if (sth == THINGB){
// do B;
}
eles{
// do C;
}
log_status("current status: - %s", sth);
}
sth is a string contains a substring in the format of xx:xx:xx:xx:xx:xx where x is either a number or a letter. The substring has a space in front of it but might not have one at the end of the string. I need to obfuscate this substring with a *. Since only the substring has :, I made a helper function to locate the first : and the last : and remove 2 characters before it. Delete the last 2 characters and append a *. I think this way is most the best solution. So I'm wondering if there are any more efficient design of a helper function aka a helper function has shorter runtime and uses less memory. Since the substring xx:xx:xx:xx:xx:xx has a very distinguish format, the only easier way I can think of is to do a string match to find the substring and then replace it with a *. I'm open to other more innovative way though.

#ifndef PARSER_STACK_H_INCLUDED
#define PARSER_STACK_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PATTERN_LEN 18
typedef struct{
unsigned int start;
unsigned int finish;
}index;
void remove_str_pattern(char *original, char *extract, unsigned int start, unsigned int finish);
void splitter(char *x, index *index_SF);
unsigned int count_points(const char *x);
void obscure(char *str, index index_SF);
char* return_obscure_string(char *str);
char* return_pattern(char *str);
char* return_pattern(char *str){
index index_SF = {0,0};
char *str_export = calloc(PATTERN_LEN, sizeof(char));
char *tmp = calloc(sizeof(str)/sizeof(char), sizeof(char));
strcpy(tmp, str);
splitter(str, &index_SF);
obscure(tmp, index_SF);
remove_str_pattern(str, str_export, index_SF.start, index_SF.finish);
return str_export;
}
char* return_obscure_string(char *str){
index index_SF = {0,0};
char *str_export = calloc(PATTERN_LEN, sizeof(char));
char *tmp = calloc(sizeof(str)/sizeof(char), sizeof(char));
strcpy(tmp, str);
splitter(str, &index_SF);
obscure(tmp, index_SF);
remove_str_pattern(str, str_export, index_SF.start, index_SF.finish);
return tmp;
}
void obscure(char *str, index index_SF){
for(unsigned int i = index_SF.start; i < index_SF.finish+1; ++i){
if(str[i] != ':'){
str[i] = '*';
}
}
}
void splitter(char *x, index *index_SF){
for(unsigned int i = 0, tmp = 0; i < strlen(x); ++i){
if(x[i] == ':'){
++tmp;
if(tmp == 1){
index_SF->start = i-2;
}else{
if(tmp == 5){
index_SF->finish = i+2;
}
}
}
}
}
unsigned int count_points(const char *x){
int c = 1;
for(unsigned int i = 0; i < strlen(x); ++i){
if((x[i] == ':' && x[i+2] == ':') || (x[i] == ':' && x[i-2] == ':')){
++c;
}
}
return c;
}
void remove_str_pattern(char *original, char *extract, unsigned int start, unsigned int finish){
for(unsigned int i = start, j = 0; i < finish+1; ++i, ++j){
extract[j] = original[i];
}
}
#endif // PARSER_STACK_H_INCLUDED
That is my personal header file for your request, create header file with this code and try it ! :D
Two "main" functions of this file are.
1. char* return_obscure_string(char *str);
For return original string with obscured sub-string..
2. char* return_pattern(char *str);
For return pattern value from a string..
Good Luck Man !

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PATTERN_LEN 18
typedef struct{
unsigned int start;
unsigned int finish;
}index;
void remove_str_pattern(char *original, char *extract, unsigned int start, unsigned int finish);
void splitter(char *x, index *index_SF);
unsigned int count_points(const char *x);
void obscure(char *str, index index_SF);
void main(){
index index_SF = {0,0};
char *origin = "this is first try for me in stack aa:bb:22:44:55:66 overflow...";
char *str_export = calloc(PATTERN_LEN, sizeof(char));
char *tmp = calloc(sizeof(origin)/sizeof(char), sizeof(char));
strcpy(tmp, origin);
splitter(origin, &index_SF);
obscure(tmp, index_SF);
remove_str_pattern(origin, str_export, index_SF.start, index_SF.finish);
printf("start index: %u finish index: %u\n", index_SF.start, index_SF.finish);
printf("obscured string %s\n", tmp);
printf("original str: %s\n", origin);
printf("pattern: %s\n", str_export);
}
void obscure(char *str, index index_SF){
for(unsigned int i = index_SF.start; i < index_SF.finish+1; ++i){
if(str[i] != ':'){
str[i] = '*';
}
}
}
void splitter(char *x, index *index_SF){
for(unsigned int i = 0, tmp = 0; i < strlen(x); ++i){
if(x[i] == ':'){
++tmp;
if(tmp == 1){
index_SF->start = i-2;
}else{
if(tmp == 5){
index_SF->finish = i+2;
}
}
}
}
}
unsigned int count_points(const char *x){
int count = 1;
for(unsigned int i = 0; i < strlen(x); ++i){
if((x[i] == ':' && x[i+2] == ':') || (x[i] == ':' && x[i-2] == ':')){
++count;
}
}
return count;
}
void remove_str_pattern(char *original, char *extract, unsigned int start, unsigned int finish){
for(unsigned int i = start, j = 0; i < finish+1; ++i, ++j){
extract[j] = original[i];
}
}

Related

Need to sort a string input by the most frequent characters first in C (qsort)

I managed to sort it alphabetically but I need to sort it by the most frequent characters first after that. Since I'm new to C programming Im not sure if this alphabetical sort is needed. Also I thought about using a struct but not sure how to do the whole process with it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmpfunc(const void *a, const void *b) {
return *(char*)a - *(char*)b;
}
void AlphabetOrder(char str[]) {
qsort(str, (size_t) strlen(str), (size_t) sizeof(char), cmpfunc);
printf("%s\n", str);
}
void Max_Occurring(char *str)
{
int i;
int max = 0;
int freq[256] = {0};
for(i = 0; str[i] != '\0'; i++)
{
freq[str[i]] = freq[str[i]] + 1;
}
for(i = 0; i < 256; i++)
{
if(freq[i] > freq[max])
{
max = i;
}
}
printf("Character '%c' appears %d times", max, freq[max], str);
}
int main() {
char str1[20];
printf("Enter a string: ");
scanf("%s", &str1);
AlphabetOrder(str1);
Max_Occurring(str1);
return 0;
}
I wrote you a frequency sorter using the idea that #WeatherVane mentioned:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct cfreq {
unsigned char c;
int freq;
};
int freqcmp(const void *a, const void *b) {
struct cfreq *a2 = (struct cfreq *) a;
struct cfreq *b2 = (struct cfreq *) b;
if(a2->freq < b2->freq) return -1;
if(a2->freq == b2->freq) return 0;
return 1;
}
int freqcmpdesc(const void *a, const void *b) {
return -freqcmp(a, b);
}
void FrequencyOrder(const char str[]) {
struct cfreq cfreqs[256];
for(int i = 0; i < sizeof(cfreqs) / sizeof(*cfreqs); i++) {
cfreqs[i].c = i;
cfreqs[i].freq = 0;
}
for(int i = 0; str[i]; i++) cfreqs[str[i]].freq++;
qsort(cfreqs, sizeof(cfreqs) / sizeof(*cfreqs), sizeof(*cfreqs), freqcmpdesc);
for(int i = 0; i < sizeof(cfreqs) / sizeof(*cfreqs); i++) {
if(cfreqs[i].freq) printf("%c", cfreqs[i].c);
}
printf("\n");
}
int main() {
char str1[20];
printf("Enter a string: ");
scanf("%s", &str1);
FrequencyOrder(str1);
return 0;
}
and here is a sample session (note: output is not deterministic for letters with same frequency):
Enter a string: buzz
zbu
If you want duplicate letters in the output then replace the print with a loop along these lines:
while(cfreqs[i].freq--) printf("%c", cfreqs[i].c);
Im not sure if this alphabetical sort is needed.
It is not needed, yet if done, Max_Occurring() can take advantage of a sorted string.
Since the string is sorted before calling Max_Occurring(), compute the max occurring via a count of adjacent repetitions of each char.
// Untested illustrative code.
// str points to a sorted string.
void Max_Occurring(const char *str) {
char max_ch = '\0';
size_t max_occurence = 0;
char previous = '\0';
size_t occurrence = 0;
while (*str) {
if (*str == previous) {
occurrence++;
} else {
occurrence = 1;
}
if (occurrence > max_occurence) {
max_occurence = occurrence;
max_ch = *str;
}
previous = *str;
str++;
}
printf("Character '%c' appears %zu times", max_ch, max_occurence);
}
In the case of multiple characters with the same max occurrence, this code only reports one max.
Avoid buffer overflow
Do not use scanf("%s"... without a width limit.
Tip: enable all warnings to save time and see the problem of using &str1 when str1 should be used.
char str1[20];
...
// scanf("%s", &str1);
scanf("%19s", str1);
Avoid a negative index
If still wanting to for a frequency table, watch out for the case when char is signed and code use str[i] < 0 to index an array.
Instead:
const unsigned char *ustr = (const unsigned char *) str;
size_t freq[UCHAR_MAX + 1] = {0};
for(size_t i = 0; ustr[i] != '\0'; i++) {
freq[ustr[i]]++;
}
Here's another alternative that may be simpler.
void freqOrder( char *p ) {
#define ASCIIcnt 128 // 7bit ASCII
// to count occurences of each character
int occur[ ASCIIcnt ];
memset( occur, 0, sizeof occur );
int maxCnt = 0; // remember the highest count
// do the counting
for( ; *p; p++ )
if( ++occur[ *p ] > maxCnt )
maxCnt = occur[ *p ];
// output most frequent to least frequen
for( ; maxCnt; maxCnt-- )
for( int i = 0; i < ASCIIcnt; i++ )
if( occur[i] == maxCnt )
while( occur[i]-- )
putchar( i );
putchar( '\n' );
}
int main( void ) {
freqOrder( "The quick brown fox jumps over the lazy dog" );
return 0;
}
Output
' ooooeeehhrruuTabcdfgijklmnpqstvwxyz'

String length always 0

I am trying to teach myself C,so I am writing a program to see if a string is present at the end of another string.
#include <stdio.h>
#include <stdlib.h>
int containsAtEnd(char *s, char *t);
int strlen(char *s);
int main()
{
char *x = "tacocat";
char *y = "bol";
printf("%d\n", strend(x, y));
getchar();
return 0;
}
int strlen(char *s)
{
int i;
for (i = 0; i != '\0'; ++i)
;
printf("%d", i);
return i;
}
int containsAtEnd(char *s, char *t)
{
int tlen = strlen(*t);
int slen = strlen(*s);
int i = 0;
s += slen - tlen;
while ((*s == *t) && *s != '\0')
i++; s++; t++;
if (i < (tlen-1))
return 0;
else
return 1;
}
Yet, regardless of the strings given in the main function, "001" is always printed, indicating that the length of both the strings in 0 and the second string is present in the first.
Please try if the following code can help you. I would also advice you to use an IDE or an analysis program that tells you about taking pointer from integer without a cast and conditions that are always true (or always false).
#include <stdio.h>
int containsAtEnd(char *s, char *t);
int strlen(char *s);
int strlen(char *s)
{
int i;
for (i = 0; s[i] != '\0'; ++i)
;
printf("%d", i);
return i;
}
int containsAtEnd(char *s, char *t)
{
int tlen = strlen(t);
int slen = strlen(s);
int i = 0;
s += slen - tlen;
while ((*s == *t) && *s != '\0') {
i++; s++; t++;
}
if (i < (tlen-1))
return 0;
else
return 1;
}
int main()
{
char *x = "tacocat";
char *y = "bol";
printf("%d\n", containsAtEnd(x, y));
char *x2 = "foobarbaz";
char *y2 = "bar";
printf("%d\n", containsAtEnd(x2, y2));
getchar();
return 0;
}

expands shorthand notations like 1-3 in the string to array of strings in C

Lets say I have a string XYZ1-3.
I would like to convert it to a array of strings.
XYZ1,
XYZ2,
XYZ3.
is there an elegant way to do it in C?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **expand(const char *string, int *num){//num : out var
char *id = strdup(string);
int start, end, len;
sscanf(string, "%*[A-Z]%n%d-%d", &len, &start, &end);
id[len] = '\0';
*num = end-start+1;
char **array = malloc(*num * sizeof(char*));
for(int i=0;i < *num ;++i){
len = snprintf(NULL, 0, "%s%d", id, start + i);
array[i] = malloc(++len);
sprintf(array[i], "%s%d", id, start + i);
}
free(id);
return array;
}
int main(){
int n;
char **array = expand("XYZ1-3", &n);
for(int i=0;i<n;++i){
printf("%s\n", array[i]);
free(array[i]);
}
free(array);
return 0;
}
Allow the non-alphabetical(not A-Z) id part
#include <ctype.h>
int id_length(const char *string){
//return length of id part.
int i, len;
for(i=0;string[i];++i);
if(i==0)return 0;
for(i=i-1;isdigit(string[i]) && i>=0;--i);
if(string[i]!='-') return 0;//bad format
for(i=i-1;isdigit(string[i]) && i>=0;--i);
return i+1;
}
char **expand(const char *string, int *num){//num : out var
char *id = strdup(string);
int start, end, len;
len = id_length(string);
sscanf(string+len, "%d-%d", &start, &end);
id[len] = '\0';
*num = end-start+1;
char **array = malloc(*num * sizeof(char*));
for(int i=0;i < *num ;++i){
len = snprintf(NULL, 0, "%s%d", id, start + i);
array[i] = malloc(++len);
sprintf(array[i], "%s%d", id, start + i);
}
free(id);
return array;
}
Try this--
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int len,i,c,d,p,j;
char arr[50];
char arr2[50];
char arr3[30][30];
char temp[30];
scanf("%s",arr);
len=strlen(arr);//calculating length of entire input
for(i=0;i<len;i++)
{
if(arr[i]!='-')
arr2[i]=arr[i];//arr2[] will hold the string without the numeral
else
break;
}
c=(int)arr[i-1]-48;//char is converted into int
d=(int)arr[i+1]-48;
for(i=0;i<len-3;i++)
temp[i]=arr2[i];
p=0;
for(i=c;i<=d;i++)
{
temp[len-3]=(char)(i+48);//int is converted into character
for(j=0;j<=len-3;j++)
arr3[p][j]=temp[j];//this 2d array holds array of strings
p++;
}
for(i=0;i<=(d-c);i++)
{
for(j=0;j<=len-3;j++)
{
printf("%c",arr3[i][j]);//printing the strings one by one
}
printf("\n");
}
getch();
}

Reverse characters word in array

for exemple i need to invers "Paris" to "siraP"...
My main:
int main(void)
{
char w1[] = "Paris";
ReverseWord(w1);
printf("The new word is: %s",w1);
return0;
}
and my function:
void ReverseWord(char *Str)
{
int counter=0;
for(int i=0; *(Str+i)!='\0'; i++)
counter++;
int length = counter-1;
char temp[length];
for(int j=0; temp[j]=='\0'; j++)
temp[j]=Str[length-j];
}
Now I have my renverse word in temp[].
I need to put it in my pointer *Str.
How can I do it??
Thanks
If you want use temp must then your function like this
void ReverseWord(char *Str)
{
int i,j;
if(str)
{
int length=strlen(Str);
char temp[length+1];
for( j=0; j<length; j++)
temp[j]=Str[length-1-j];
temp[j]='\0';
strcpy(Str,temp);
}
}
Without using temp as follows
void ReverseWord(char *Str)
{
int end= strlen(Str)-1;
int start = 0;
while( start<end )
{
Str[start] ^= Str[end];
Str[end] ^= Str[start];
Str[start]^= Str[end];
++start;
--end;
}
}
void ReverseWord(char *Str)
{
size_t len;
char temp, *end;
len = strlen(Str);
if (len < 2)
return;
end = Str + len - 1;
while (end > Str)
{
temp = *end;
*end-- = *Str;
*Str++ = temp;
}
}
One more option, this time with dangerous malloc(3).
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *rev(char s[]) {
char *buf = (char *)malloc(sizeof(char) * strlen(s));
int i, j;
if(buf != NULL)
for(i = 0, j = strlen(s) - 1; j >= 0; i++, j--)
buf[i] = s[j];
return buf;
}
int main(int argc, char **argv) {
printf("%s\n", rev(argv[1]));
return 0;
}
Run with "foo bar foobar baz" and get zab raboof rab oof back:
~/tmp$ ./a.out "foo bar foobar baz"
zab raboof rab oof
Here I think you can study two algorithms:
C string length calculate: the end of the c string is '\0'
How to reverse a c string in place
And if you need to test the code, you should alloc testing strings in heap or strack. If you write a literal string, you may meet a bus error because of the literal string being saved in text-area which is a read only memory.
And the following is the demo:
#include <stdio.h>
#include <stdlib.h>
void reverse_string(char* str)
{
size_t len;
char tmp, *s;
//Get the length of string, in C the last char of one string is \0
for(s=str;*s;++s) ;
len = s - str;
//Here we use the algorithm for reverse the char inplace.
//We only need a char tmp place for swap each char
s = str + len - 1;
while(s>str){
tmp = *s;
*s = *str;
*str = tmp;
s--;
str++;
}
}
int main()
{
char* a = "abcd";
//Here "abcd" will be saved in READ Only Memory. If you test code, you will get a bus error.
char* b = (char*)calloc(1,10);
strcpy(b,a);
reverse_string(b);
printf("%s\n",b);
a = "abcde";
strcpy(b,a);
reverse_string(b);
printf("%s\n",b);
}
you can do it simply by following code
for(int k=0;k<strlen(temp);k++)
{
Str[k]=temp[k];
}

replaceString() function in C

I am currently learning C with the book "Programming in C 3rd edition" by Stephen G. Kochan.
The exercise require that I make a function that replaces a character string inside a character string with another character string. So the function call
replaceString(text, "1", "one");
Will replace, if exist, "1" in the character string text with "one".
To fullfill this exercise, you need the functions findString(), insertString() and removeString().
This is the findString() function
int findString (const char source[], const char s[])
{
int i, j;
bool foundit = false;
for ( i = 0; source[i] != '\0' && !foundit; ++i )
{
foundit = true;
for ( j = 0; s[j] != '\0' && foundit; ++j )
if ( source[j + i] != s[j] || source[j + i] == '\0' )
foundit = false;
if (foundit)
return i;
}
return -1;
}
If s[] is inside the string source[], it returns an integer equal to the starting point for s[] inside the string. If it do not find s[] it will return -1.
The insertString() function is as follows
void insertString (char source[], char s[], int index)
{
int stringLength (char string[]);
int j, lenS, lenSource;
lenSource = stringLength (source);
lenS = stringLength (s);
if ( index > lenSource )
return;
for ( j = lenSource; j >= index; --j )
source[lenS + j] = source[j];
for ( j = 0; j < lenS; ++j )
source[j + index] = s[j];
}
This function take three arguments i.e. source[], s[] and index[]. s[] is the string that I would like to put into source[] and index[] is where it should start (e.g. insertString("The son", "per", 4) makes the source string to "The person").
The function includes another function called stringLength(), which purpose is the same at its name. This is stringLength()
int stringLength (char string[])
{
int count = 0;
while ( string[count] != '\0' )
++count;
return count;
}
The removeString() takes three arguments i.e. word, i and count. The function removes a number of characters inside another character string. This function I have not yet been able to make.
Just to sum it up, my question is:
How do i make the function replaceString(), which looks for a word in a character string, and if it is there, then it replaces it with another?
This has really bugged me for some time, and I would really appreciate your help on this.
UPDATE
This is the code I have made so far
// replaceString() program
#include <stdio.h>
#include <stdbool.h>
int findString (char source[], char s[])
{
int i, j;
bool foundit = false;
for ( i = 0; source[i] != '\0' && !foundit; ++i )
{
foundit = true;
for ( j = 0; s[j] != '\0' && foundit; ++j )
if ( source[j + i] != s[j] || source[j + i] == '\0' )
foundit = false;
if (foundit)
return i;
}
return -1;
}
int stringLength (char string[])
{
int count = 0;
while ( string[count] != '\0' )
++count;
return count;
}
void replaceString(char source[], char str1[], char str2[])
{
int findString(char source[], char s[]);
int stringLength(char string[]);
int start;
if ( findString(source, str1) == -1 )
return;
else
{
start = findString(source, str1);
int lenSource = stringLength(source);
int lenStr2 = stringLength(str2);
int counter = lenStr2;
for ( lenSource; lenSource > start + lenStr2; --lenSource )
{
source[lenSource + lenStr2] = source[lenSource];
}
int i = 0;
while ( i != counter )
{
source[start + i] = str2[i];
++i;
}
}
}
int main (void)
{
void replaceString(char source[], char str1[], char str2[]);
char string[] = "This is not a string";
char s1[] = "not";
char s2[] = "absolutely";
printf ("Before: \n %s \n\n", string);
replaceString(string, s1, s2);
printf ("After: \n %s \n\n", string);
return 0;
}
This code gives the following output:
Before:
This is not a string
After:
This is absolutelyng
As you can see, I have not included the removeString function(), as I could not get that function working properly. Where is the error in my program?
for starters, your string's length is fixed. so if the "destination" is longer than "source", then it won't work. insert string needs to pass in a pointer, then you can allocate a string on the heap that is long enough to contain length(source)-length(remove) +length(add), and return that pointer
Say your replaceString() args are (char source[], char s1[], char replacement[])
You need to use findString() to find s1 in source. If it finds it, given the position of s1, use removeString() to remove that string and then insertString() to insert replacement into that position.
I am also a newbie in programming. I came across this same exercise some days ago and just solved it today.
This is my code.
/* Programme to replace a string by using find, remove and insert
functions ex9.8.c */
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define MAX 501
// Function prototypes
void read_Line (char buffer[]);
int string_Length (char string[]);
int find_String (char string1[], char string2[]);
void remove_String (char source[], int start, int number);
void insert_String (char source[], int start, char input[]);
void replace_String (char origString[], char targetString[], char substString[]);
bool foundFirstCharacter = false;
int main(void)
{
printf("This is a programme to replace part of a string.\n");
printf("It can only handle up to 500 characters in total!\n");
char text[MAX];
bool end_Of_Text = false;
int textCount = 0;
printf("\nType in your source text.\n");
printf("When you are done, press 'RETURN or ENTER'.\n\n");
while (! end_Of_Text)
{
read_Line(text);
if (text[0] == '\0')
{
end_Of_Text = true;
}
else
{
textCount += string_Length(text);
}
break;
}
// Declare variables to store seek string parameters
int seekCount = 0;
char seekString[MAX];
printf("\nType in the string you seek.\n");
printf("When you are done, press 'RETURN or ENTER'.\n\n");
while (! end_Of_Text)
{
read_Line(seekString);
if (seekString[0] == '\0')
{
end_Of_Text = true;
}
else
{
seekCount += string_Length(seekString);
}
break;
}
// Declare variables to store replacement string parameters
int replCount = 0;
char replString[MAX];
printf("\nType in the replacement string.\n");
printf("When you are done, press 'RETURN or ENTER'.\n\n");
while (! end_Of_Text)
{
read_Line(replString);
if (replString[0] == '\0')
{
end_Of_Text = true;
}
else
{
replCount += string_Length(replString);
}
break;
}
// Call the function
replace_String (text, seekString, replString);
return 0;
}
// Function to get text input
void read_Line (char buffer[])
{
char character;
int i = 0;
do
{
character = getchar();
buffer[i] = character;
++i;
}
while (character != '\n');
buffer[i - 1] = '\0';
}
// Function to determine the length of a string
int string_Length (char string[])
{
int len = 0;
while (string[len] != '\0')
{
++len;
}
return len;
}
// Function to find index of sub-string
int find_String (char string1[], char string2[])
{
int i, j, l;
int start;
int string_Length (char string[]);
l = string_Length(string2);
for (i = 0, j = 0; string1[i] != '\0' && string2[j] != '\0'; ++i)
{
if (string1[i] == string2[j])
{
foundFirstCharacter = true;
++j;
}
else
{
j = 0;
}
}
if (j == l)
{
start = i - j + 1;
return start;
}
else
{
return j - 1;
}
}
// Function to remove characters in string
void remove_String (char source[], int start, int number)
{
int string_Length (char string[]);
int i, j, l;
char ch = 127;
l = string_Length(source);
j = start + number;
for (i = start; i < j; ++i)
{
if (i >= l)
{
break;
}
source[i] = ch;
}
//printf("\nOutput: %s\n", source);
}
// Function to insert characters in string
void insert_String (char source[], int start, char input[])
{
int string_Length (char string[]);
int i, j, k, l, m;
int srcLen;
int inpLen;
int totalLen;
int endInsert;
srcLen = string_Length(source);
inpLen = string_Length(input);
// Declare buffer array to hold combined strings
totalLen = srcLen + inpLen + 3;
char buffer[totalLen];
// Copy from source to buffer up to insert position
for (i = 0; i < start; ++i)
buffer[i] = source[i];
// Copy from input to buffer from insert position to end of input
for (j = start, k = 0; k < inpLen; ++j, ++k)
buffer[j] = input[k];
endInsert = start + inpLen;
for (m = start, l = endInsert; m <= srcLen, l < totalLen; ++m, ++l)
buffer[l] = source[m];
buffer[l] = '\0';
printf("\nOutput: %s\n", buffer);
}
// Function to replace string
void replace_String (char origString[], char targetString[], char substString[])
{
// Function prototypes to call
void read_Line (char buffer[]);
int string_Length (char string[]);
int find_String (char string1[], char string2[]);
void remove_String (char source[], int start, int number);
void insert_String (char source[], int start, char input[]);
// Search for target string in source text first
int index;
index = find_String (origString, targetString);
if (index == -1)
{
printf("\nTarget string not in text. Replacement not possible!\n");
exit(999);
}
// Remove found target string
int lengthTarget;
lengthTarget = string_Length(targetString);
remove_String(origString, index - 1, lengthTarget);
// Insert replacement string
insert_String(origString, index, substString);
}

Resources