I am trying to reverse this C-string and I thought I did it correct but the string remains the same when it passes through the function.
#include <stdio.h>
char* reverse(char* string);
int main(int arc, char* argv[]) {
char word[] = "Hello World!";
printf("%s\n", word);
printf("%s\n", reverse(word));
return 0;
}
char* reverse(char* string) {
int i, j, n = 0;int len = 0;char temp;
//Gets string length
for (i = 0; *(string + i) != '0'; i++) {
len++;
}
//Reverses string
for (j = len - 1; j >= 0; j--) {
temp = string[n];
string[n] = string[j];
string[j] = temp;
n++;
}
return &string[0];
}
Expected output:
Hello World!
!dlroW olleH
For starters there is a typo
for (i = 0; *(string + i) != '0'; i++) {
You have to write
for (i = 0; *(string + i) != '\0'; i++) {
That is instead of the character '0' you have to use '\0' or 0.
In this for loop
for (j = len - 1; j >= 0; j--) {
temp = string[n];
string[n] = string[j];
string[j] = temp;
n++;
}
the string is reversed twice.:) As a result you get the same string.
The function can look for example the following way
char * reverse(char *string)
{
//Gets string length
size_t n = 0;
while ( string[n] != '\0' ) ++n;
//Reverses string
for ( size_t i = 0, m = n / 2; i < m; i++ )
{
char temp = string[i];
string[i] = string[n - i - 1];
string[n - i - 1] = temp;
}
return string;
}
Or the function can be defined the following way using pointers
char * reverse(char *string)
{
//Gets string length
char *right = string;
while ( *right ) ++right;
//Reverses string
if ( right != string )
{
for ( char *left = string; left < --right; ++left )
{
char temp = *left;
*left = *right;
*right = temp;
}
}
return string;
}
The same approach of the function implementation without using pointers can look the following way
char * reverse(char *string)
{
//Gets string length
size_t n = 0;
while ( string[n] != '\0' ) ++n;
//Reverses string
if ( n != 0 )
{
for ( size_t i = 0; i < --n; ++i )
{
char temp = string[i];
string[i] = string[n];
string[n] = temp;
}
}
return string;
}
Here is one more solution. I like it most of all. Tough it is inefficient but it is not trivial as the early presented solutions. It is based on an attempt of one beginner to write a function that reverses a string.:)
#include <stdio.h>
#include <string.h>
char *reverse( char *string )
{
size_t n = 0;
while (string[n]) ++n;
while (!( n < 2 ))
{
char c = string[0];
memmove( string, string + 1, --n );
string[n] = c;
}
return string;
}
int main( void )
{
char string[] = "Hello World!";
puts( string );
puts( reverse( string ) );
}
The program output is
Hello World!
!dlroW olleH
Of course instead of manually calculating the length of a string in all the presented solutions there could be used standard string function strlen declared in the header <string.h>.
The problem is that the input word[] is an array, which decays to a pointer when passed to the reverse function.
In the for loop, instead of using n to keep track of the position, I suggest you to use i and j to keep track of the start and end of the string, and increment and decrement them respectively and use strlen to get the length of string.
Also, as it is mentionned above by #Vlad from Moscow, in your for loop you are checking for 0 but it should be \0 which is the null character.
Please find down below an update of your posted code that is generating the expected result :
#include <stdio.h>
char* reverse(char* string);
int main(int arc, char* argv[]) {
char word[] = "Hello World!";
printf("%s ", word);
printf("%s\n", reverse(word));
return 0;
}
char* reverse(char* string) {
int i, j;
char temp;
int len = strlen(string);
//Reverses string
for (i = 0, j = len - 1; i < j; i++, j--) {
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
return &string[0];
}
The output is as expected: Hello World! !dlroW olleH
Aditionnally, you can include the header <string.h> or explicitly
provide a declaration for 'strlen' to avoid the warning that indicate to implicitly declaring library function 'strlen' with type 'unsigned long (const char *)' [-Wimplicit-function-declaration]
Related
zfill algorithm is supposed to work as follows:
zfill function accepts two parameters, a string and a number,
if string length is >= the number, then it doesn't have to add anything, and it returns a copy to the string,
else, malloc enough space and add zeros before the string.
I'm trying to understand why is this solution not correct, it has two warnings:
1st warning:
for (i; i < zeros; i++) {
s[i] = "0";
}
"=": char differs in level of indirection from char[2]
2nd warning:
for (i; i < n; i++) {
s[i] = str[i];
}
buffer overrun while writing to s
char* zfill(const char* str, size_t n) {
if (str == NULL) {
return NULL;
}
char* s;
size_t length = strlen(str);
if (length >= n) {
//it doesn't have to add anything, just malloc and copy the string
size_t sum = length + 1u;
s = malloc(sum);
if (s == NULL) {
return NULL;
}
for (size_t i = 0; i < length; i++) {
s[i] = str[i];
}
s[sum] = 0;
}
else {
// add zeros before strings
size_t zeros = n - length;
size_t sum = n + 1u;
s = malloc(sum);
if (s == NULL) {
return NULL;
}
size_t i = 0;
for (i; i < zeros; i++) {
s[i] = "0";
}
for (i; i < n; i++) {
s[i] = str[i];
}
s[sum] = 0;
}
return s;
}
int main(void) {
char str[] = "hello, world!";
size_t n = 40;
char* s = zfill(str, n);
free(s);
return 0;
}
EDIT: I've solved the problem this way:
char* zfill(const char* str, size_t n) {
if (str == NULL) {
return NULL;
}
char* s;
size_t length = strlen(str);
if (length >= n) {
//it doesn't have to add anything, just malloc and copy the string
size_t sum = length + 1u;
s = malloc(sum);
if (s == NULL) {
return NULL;
}
for (size_t i = 0; i < length; i++) {
s[i] = str[i];
}
s[sum-1] = 0;
}
else {
// add zeros before strings
size_t zeros = n - length;
size_t sum = n + 1u;
s = malloc(sum);
if (s == NULL) {
return NULL;
}
size_t i = 0;
for (i; i < zeros; i++) {
s[i] = '0';
}
for (size_t j = 0; i < n; j++) {
s[i++] = str[j];
}
s[sum-1] = 0;
}
return s;
}
and it works, but I don't know why I have this warning:
for (i; i < zeros; i++) {}
statement with no effect
but when I've debugged I've noticed that this statement has an effect, because it correctly copies the correct number of zeros. I don't know why I have this warning
SO is a place of learning.
When first dealing with a coding challenge, it's best to take time to work out what's needed before starting to write code.
Below is a working version of zfill() (along with a main() that tests it.)
Read through the comments. The only thing new here is memset().
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// A trivial "helper function" determines the max of two values
int max( int a, int b ) { return a > b ? a : b; }
char *zfill( char *str, int minLen ) {
// Determine length of arbitrary string
int len = strlen( str );
// Determine max of length v. minimum desired
int allocSize = max( minLen, len );
// allocate buffer to store resulting string (with '\0')
char *obuf = (char*)malloc( allocSize + 1 );
/* omitting test for failure */
// determine start location at which to copy str
int loc = len <= minLen ? minLen - len : 0;
if( loc > 0 )
// fill buffer with enough 'zeros'
memset( obuf, '0', allocSize ); // ASCII zero!
// copy str to that location in buffer
strcpy( obuf + loc, str );
// return buffer to calling function
return obuf;
}
int main() {
// collection of strings of arbitrary length
char *strs[] = { "abc", "abcdefghijkl", "abcde", "a", "" };
// pass each one to zfill, print, then free the alloc'd buffer.
for( int i = 0; i < sizeof strs/sizeof strs[0]; i++ ) {
char *cp = zfill( strs[i], 10 );
puts( cp );
free( cp );
}
return 0;
}
Output:
0000000abc
abcdefghijkl
00000abcde
000000000a
0000000000
Here's zfill() without the comments:
char *zfill( char *str, int minLen ) {
int len = strlen( str );
int allocSize = max( minLen, len );
char *obuf = (char*)malloc( allocSize + 1 );
/* omitting test for failure */
int loc = len <= minLen ? minLen - len : 0;
if( loc > 0 )
memset( obuf, '0', loc ); // ASCII zero!
strcpy( obuf + loc, str );
return obuf;
}
You don't want to spend your time staring at lines and lines of code.
Fill your quiver with arrows that are (proven!) standard library functions and use them.
I've omitted, too, the test for zfill being passed a NULL pointer.
This code snippet
size_t sum = length + 1u;
s = malloc(sum);
//...
s[sum] = 0;
accesses memory outside the allocated character array because the valid range of indices is [0, sum). You need to write at least like
s[length] = 0;
In this code snippet
for (i; i < zeros; ++) {
s[i] = "0";
}
the expression s[i] represents a single object of the type char while on the right-hand side there is a string literal that as an expression has the type char *. You need to write at least
s[i] = '0';
using the integer character constant instead of the string literal.
In this code snippet
size_t i = 0;
for (i; i < zeros; i++) {
s[i] = "0";
}
for (i; i < n; i++) {
s[i] = str[i];
}
as the length of the string str can be less than n then this for loop
for (i; i < n; i++) {
s[i] = str[i];
}
accesses memory outside the string str.
Pay attention to that your function has redundant code. It can be written simpler.
The function can look for example the following way as shown in the demonstration program below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * zfill( const char *s, size_t n )
{
char *result = NULL;
if ( s != NULL )
{
size_t len = strlen( s );
n = len < n ? n : len;
result = malloc( n + 1 );
if ( result )
{
size_t i = 0;
size_t m = len < n ? n - len : 0;
for ( ; i < m; i++ )
{
result[i] = '0';
}
for ( ; i < n; i++ )
{
result[i] = s[i - m];
}
result[i] = '\0';
}
}
return result;
}
int main( void )
{
const char *s = "Hello";
size_t n = 10;
char *result = zfill( s, n );
if ( result ) puts( result );
free( result );
}
The program output is
00000Hello
Or as #Some programmer dude pointed to in his comment you can use the standard C function snprintf that alone performs the task. For example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * zfill( const char *s, size_t n )
{
char *result = NULL;
if ( s != NULL )
{
size_t len = strlen( s );
n = len < n ? n : len;
result = malloc( n + 1 );
if ( result )
{
int m = len < n ? n - len : 0;
snprintf( result, n + 1, "%.*d%s", m, 0, s );
}
}
return result;
}
int main( void )
{
char *p = zfill( "Hello", 5 );
if ( p ) puts( p );
free( p );
p = zfill( "Hello", 10 );
if ( p ) puts( p );
free( p );
}
The program output is
Hello
00000Hello
so you have 3 major problems in your code :
it's s[i] = '0'; not s[i] = "0";
it's s[i] = str[i - zeros]; not s[i] = str[i]; as the value of the i will be 27 in your test case : so it make sense to say s[27] because its size is about 41 but it doesn't make sense to say str[27] as its size is only about 13 in your test case , so you had to map the value 27 of i to the value 0 to be convenient to use with str
i is deprecated in first part here for (i; i < zeros; i++) , so use for (; i < zeros; i++)instead of for (i; i < zeros; i++) , but it will not cause any problem if you keep it.
and here is the full edited code :
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* zfill(const char* str, size_t n) {
if (str == NULL) {
return NULL;
}
char* s;
size_t length = strlen(str);
if (length >= n) {
//it doesn't have to add anything, just malloc and copy the string
size_t sum = length + 1u;
s = malloc(sum);
if (s == NULL) {
return NULL;
}
for (size_t i = 0; i < length; i++) {
s[i] = str[i];
}
s[sum] = 0;
}
else {
// add zeros before strings
size_t zeros = n - length;
size_t sum = n + 1u;
s = malloc(sum);
if (s == NULL) {
return NULL;
}
size_t i = 0;
for (; i < zeros; i++) {
s[i] = '0';
}
for (; i < n; i++) {
s[i] = str[i - zeros];
}
s[sum] = 0;
}
return s;
}
int main(void) {
char str[] = "hello, world!";
size_t n = 40;
char* s = zfill(str, n);
printf("%s\n", s);
free(s);
return 0;
}
I am trying to write a function that reverses a given string but it gives me "stack smashing detected".
Here is my code:
void reverse(char *str2) {
int i, j;
char temp;
for (i = 0, j = str2[strlen(str2) - 1]; i < j; i++, j--) {
temp = str2[i];
str2[i] = str2[j];
str2[j] = temp;
}
str2[strlen(str2)] = '\0';
printf("%s", str2);
}
There are multiple problems in your code:
j should be initialized as j = strlen(str2) - 1, not j = str2[strlen(str2) - 1] which is the value of the last character in the string (if any).
str2[strlen(str2)] = '\0'; is absolutely useless and redundant.
Here is a modified version:
#include <stdio.h>
#include <string.h>
void reverse(char *str) {
for (size_t i = 0, j = strlen(str); i < j--; i++) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
printf("%s\n", str);
}
Such a function should return a pointer to the reversed string. That is it is better to declare the function like
char * reverse( char *str2 );
Also the name of the parameter looks strange. So declare the function like
char * reverse( char *s );
There is a typo in the function. The variable j must be initialized like
j = strlen( str2 ) - 1;
instead of
j = str2[strlen(str2) - 1];
This statement
str2[strlen(str2)] = '\0';
is redundant and should be removed.
The function should not output the reversed string. It is the caller of the function that will decide whether to output the reversed string.
Also instead of the type int for indices you should use the type size_t - the return type of the function strlen.
Using your approach the function should look the following way
char * reverse( char *s )
{
if ( *s )
{
for ( size_t i = 0, j = strlen( s ) - 1; i < j; i++, j-- )
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
return s;
}
Here is a demonstration program.
#include <stdio.h>
#include <string.h>
char * reverse( char *s )
{
if ( *s )
{
for ( size_t i = 0, j = strlen( s ) - 1; i < j; i++, j-- )
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
return s;
}
int main(void)
{
char s[] = "Hello World!";
puts( s );
puts( reverse( s ) );
}
Its output is
Hello World!
!dlroW olleH
Ive been trying to reverse a string as simply as possible , trying to prove a point to myself but for some reason the code is not working. I know i can easily find a different approach online but then i wont learn anything. So would anyone explain please?
#include <stdio.h>
#include <stdlib.h>
int main()
{ int i,n,c=0;
char s[50];
char a[50];
for(i = 0; i < 50;i++)
scanf("%[^\n]c",&s[i]);
for(n = strlen(s), i = 0; n > i; n--,c++)
s[c] = s[n-1];
printf("%s", s);
return 0;
}
For starters you need to include the header <string.h>.
This loop
for(i = 0; i < 50;i++)
scanf("%[^\n]c",&s[i]);
does not make a great sense. Moreover you need to append the entered string with the terminating zero character '\0'.
What you need is to enter a string one time as for example
scanf("%49s", s );
Or even better to write
scanf( "%49[^\n]", s );
to enter a string with several words in the array.
This for loop
for(n = strlen(s), i = 0; n > i; n--,c++)
s[c] = s[n-1];
also does not make a sense. It does not reverse the string. The variable i is not increased. That is you need to swap two characters.
Also you need to declare variables in minimum scopes where they are used.
The loop can look for example the following way
for ( size_t i = 0, n = strlen(s); i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n-1-i];
s[n-1-i] = c;
}
Apart from all these the declared array a is not used in the program.
So the program can look the following way
#include <stdio.h>
#include <string.h>
int main( void )
{
char s[50] = "";
scanf( "%49[^\n]", s );
for ( size_t i = 0, n = strlen(s); i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n-1-i];
s[n-1-i] = c;
}
puts( s );
}
If to enter string
Hello, unikatura!
then the program output will be
!arutakinu ,olleH
Use functions.
Two variants:
char *reverse(char *str)
{
char *end = str, *start = str;
if(str && *str)
{
for(;*(end + 1);end++);
for(;end > start;)
{
char tmp = *end;
*end-- = *start;
*start++ = tmp;
}
}
return str;
}
char *reverse1(char *dest, const char *str)
{
char *wrk = dest;
size_t len = 0;
if(str)
{
for(;*str;len++, str++);str -= !!*str;
for(;len--; *wrk++ = *str--);
}
*wrk = 0;
return dest;
}
#include <stdio.h>
void revstr(char str[])
{
char temp;
int size = 0;
while(*str != '\0'){
size++;
str++;
}
for (int i = 0; i < size/2; i++)
{
temp = str[i];
str[i] = str[size-1-i];
str[size-1-i] = temp;
}
for(int i = 0; i < size; i++)
{
printf("%c\n", *(str+i));
}
}
int main()
{
char str[20];
printf("enter a string: \n");
scanf("%s", &str);
revstr(str);
return 0;
}
why is my rev string not printing the reverse of the string it is printing out some garbage value.
can you point out why?
After this while loop
while(*str != '\0'){
size++;
str++;
}
the pointer str does not point to the beginning of the string.
Instead you could write for example
while( str[size] != '\0'){
size++;
}
Nevertheless such a function should do only one thing: to reverse a string. It is the caller of the function that decides whether to output the reversed string.
So the function can look like
char * revstr( char s[] )
{
size_t n = 0;
while ( s[n] ) ++n;
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = c;
}
return s;
}
and in main you could write
puts( revstr( str ) );
Here is a demonstrative program.
#include <stdio.h>
char * revstr( char s[] )
{
size_t n = 0;
while ( s[n] ) ++n;
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = c;
}
return s;
}
int main(void)
{
char s[] = "Hello";
puts( s );
puts( revstr( s ) );
return 0;
}
The program output is
Hello
olleH
Of course instead of the while loop you could use the standard string function strlen.
size_t n = strlen( s );
Pay attention to that in the call of scanf
scanf("%s", &str);
the second argument shall be the expression str
scanf("%s", str);
I would implement it another way:
char *reverse(char *str)
{
char *wrk = str, *end = str;
if(str && *str)
{
while(*(end + 1)) end++;
while(end > wrk)
{
char tmp = *end;
*end-- = *wrk;
*wrk++ = tmp;
}
}
return str;
}
It is good to check if the parameter is correct.
I would return the value. It allows you to use the reversed string in expressions and as a function parameter. Example below:
int main(void)
{
char s[] = "Hello world";
printf("%s\n", reverse(s));
}
https://godbolt.org/z/fbo4nsn38
In your code you advance the pointer str to calculate its length but you forgot to reset it to the start after that. Also, your call to scanf should pass str, not its address. Moreover scanf will write beyond the end of str if the user enters a string longer than 19 characters. Try this instead:
#include <stdio.h>
#include <string.h>
void revstr(char str[])
{
char temp;
int size = strlen(str);
for (int i = 0; i < size / 2; i++) {
temp = str[i];
str[i] = str[size - 1 - i];
str[size - 1 - i] = temp;
}
}
int main()
{
char str[20];
printf("enter a string: \n");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';
revstr(str);
printf("%s\n", str);
return 0;
}
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);
}