Reverse the give sentence:
#include <stdio.h>
#include <string.h>
#define STR_BUFFER_256 256
#define ARG_LENGTH 64
int reverse_sentence(char *str, char *str_result, int str_len)
{
char str_sentence[STR_BUFFER_256] = {'\0'};
char *arg[ARG_LENGTH] = {0}, *temp = NULL;
int count = 0, rev_count;
#if 0 // This logic is wrong because strncpy won't return a number of byte written
int ret = 0;
ret = strncpy(str_sentence, str, sizeof(STR_BUFFER_256));
if (ret >= STR_BUFFER_256) {
printf("Truncation the sentence \n");
}
#else
memset(str_sentence, '\0', str_len);
strncpy(str_sentence, str, str_len);
if (str_sentence[STR_BUFFER_256 - 1] != '\0') {
printf("Truncation the sentence \n");
}
#endif
#ifdef DEBUG
printf("Original = %s copied varable = %s \n", str, str_sentence);
#endif
temp = strtok(str_sentence, " ");
arg[count] = temp;
count++;
while (temp && (count < ARG_LENGTH)) {
temp = strtok(NULL, " ");
arg[count] = temp;
count++;
}
if (temp && (count >= ARG_LENGTH)) {
temp = strtok(NULL, " ");
if (temp != NULL) {
printf("No of word is more than %d so taking first %d word only\n", ARG_LENGTH, ARG_LENGTH);
}
}
/* arg[count] last value will be a NULL, but count is point to next to NUll */
count--;
/* Count point the sentinal value, decerement to point to the last word */
count--;
#ifdef DEBUG
printf("inst cout = %d rev c= %d \n", count, rev_count);
#endif
for (rev_count = count; rev_count >= 0 ; rev_count--) {
strncat(str_result, arg[rev_count], str_len);
if (rev_count != 0) {
strncat(str_result, " ", str_len);
}
}
return 0;
}
int main()
{
char str[STR_BUFFER_256] = "Velraj is coming from chennai";
char str_result[STR_BUFFER_256] = {'\0'};
reverse_sentence(str, str_result, sizeof(str_result));
printf("\n\t\t Original sentence = %s \n\t\t Reverse sentence = %s \n", str, str_result);
return 0;
}
/* Output:
------
velraj@velraj-HEC41:~/CProgram$ gcc -g sentence_reverse_hcl.c
velraj@velraj-HEC41:~/CProgram$ ./a.out
Original sentence = Velraj is coming from chennai
Reverse sentence = chennai from coming is Velraj
velraj@velraj-HEC41:~/CProgram$
'-g' is used to include the symbols, if we need to debug with gdb then compile with -g only give the
symbol value.
*/
No comments:
Post a Comment