nvseenu
BAN USERBelow code prints the word of a sentence reversely.
Since it uses recursive technique, "stack frame" of the function reverse_word is used to keep
the starting address of each word.
if number words to be printed is very huge, then we should use stack api than "stack frame"
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
struct word {
const char *start ; //start address of the word
int count; // number of characters in the word
};
void reverse_word_copy(const char *s , char *t);
static void reverse_word(const char *s , char **t);
static struct word find_word(const char *s);
static void copy(const char *s , char *t , int n );
int main(int argc , char **argv)
{
const char *s = argv[1]; // address of the argument passed;
char *t = (char *)malloc(sizeof(char) * strlen(s));
reverse_word_copy(s,t);
printf("given string => %s \n",s);
printf("reversed string => %s\n",t);
return 0;
}
void reverse_word_copy(const char *s , char *t)
{
reverse_word( s , &t );
}
static void reverse_word(const char *s , char **t)
{
struct word w = { NULL , 0 };
w = find_word( s );
if( w.count == 0 )
return;
reverse_word( w.start + w.count , t);
copy(w.start, *t,w.count);
*t = *t + w.count ; //set t to the address of next word to be written
**t = ' '; // Set space to separate the words
*t = *t +1 ; //Add one space after the word
}
static struct word find_word(const char *s)
{
struct word w = { NULL , 0 };
if(*s == 0)
return w;
/* trim white spaces front of the word */
while( *s == ' ' || *s == '\t' )
s++;
w.start = s;
while( ! ( *s == ' ' || *s == '\t' || *s == 0) ){
s++;
w.count++;
}
return w;
}
static void copy(const char *s , char *t , int n )
{
int i = 0;
for( i = 0 ; i < n ; i++ ){
*t = *s;
t++;
s++;
}
}
Apply binary search repeatedly until the match is not found.
int find_last_occurance(int key, int *p , int length)
{
int start_index = -1;
int last_index = -1;
int end_index = length -1;
while(1){
printf(">>>> starting the search in array [%d .. %d] <<< \n",start_index+1,end_index);
start_index = search(key,p,start_index+1 , end_index);
if(start_index == -1){
return last_index;
} else {
last_index = start_index;
}
}
}
nothing wrong in the implementations. the difference i see is that contents of a string created in the first implementation can be modified. whereas contents of a string in the second implementation can not be changed, since it is a string literal.
- nvseenu February 11, 2013