Reversing array logic in C not working properly - c

I am trying to read the input to my program (a string of chars) and invert the order of the words that are in it.
For example, if I were to pass my program ABC DEF GHI JKL it would output JKL GHI DEF ABC. I am using the whitespace as separators.
My code:
char toReverse[1000];
char outputArray[1000];
int charCount = //Size of the toReverse array. Varies on the input
//It is the total number of chars stored in the array
...
int i;
int tempCharCount = charCount;
int wordSize = 0;
int outputIndex = 0;
int sentenceIndex = 0;
int charStep = 0;
for(i = charCount-1; i>=0; i--){
if(toReverse[i] == ' '){
int j;
sentenceIndex = tempCharCount - wordSize;
for(j = 0; j<charStep; j++){
outputArray[outputIndex++] = toReverse[sentenceIndex++];
}
outputArray[outputIndex] = ' ';
outputIndex++;
charStep = 0;
}
wordSize++;
charStep++;
}
There is a flaw in my code. I do know why this happens though. For example, if I were to pass as input ABC DEF GHI, it will only output GHI DEF. This is because whenever the outer for loop reaches index 0 of my toReverse array, since it is not a space ' ', it does not do the if(toReverse[i]) inner for(j = 0; j<charStep; j++) since the condition is not met.
Do you have any advice regarding to the logic? I have tried reversing my logic, such as if(toReverse[i] != ' ') but it brings more problems than it solves.
Thanks for your advice and comments!
Cheers
Edit 1
I am reading my input from a file By the way!
Update 1
Here I am basically trying to open various files and read chars from them
int main(int argc, char * argv[])
{
int i = 1;
FILE * fp = NULL;
if(1==argc){
do_read(stdin);
}else{
// cycle through all files in command line arguments and read them
for (i=1; i < argc; i++) {
if ((fp = fopen(argv[i], "r")) == NULL) {
printf("Failed to open file.\n");
}
else {
do_read(fp);
fclose(fp);
}
}
}
//printf("\n");
//printf("\n");
printf("%i",charCount);
return 0;
}

sample
#include <stdio.h>
#include <string.h>
void proc_rev(char toReverse[], char outputArray[]){
int charCount = strlen(toReverse);
int i;
int tempCharCount = charCount;
int wordSize = 0;
int outputIndex = 0;
int sentenceIndex = 0;
int charStep = 0;
for(i = charCount-1; i>=0; i--){
if(toReverse[i] == ' '){
int j;
sentenceIndex = tempCharCount - wordSize;
for(j = 0; j<charStep; j++){
outputArray[outputIndex++] = toReverse[sentenceIndex++];
}
outputArray[outputIndex] = ' ';
outputIndex++;
charStep = 0;
}
wordSize++;
charStep++;
}
outputArray[outputIndex] = '\0';
}
int main(void){
FILE *fp = stdin;
char toReverse[1000] = " ";
char outputArray[1000];
while(1 == fscanf(fp, "%998[^\n]%*c", &toReverse[1])){
proc_rev(toReverse, outputArray);
puts(outputArray);
}
return 0;
}
void do_read(FILE *fp){
char toReverse[1000] = " ";
char outputArray[1000];
while(1 == fscanf(fp, "%998[^\n]%*c", &toReverse[1])){
proc_rev(toReverse, outputArray);
puts(outputArray);
}
}

This code is not tested but basic idea is reversing the whole string once and then reverse it word by word. idea is correct, implementation may have bugs
void swap(char* s, int i, int j) {
char tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
void rev(char* stirng, int start, int len) {
for (int i=0; i<len/2; ++i) {
swap(string, i, len-i-1);
}
}
int main() {
char* string = read from file
int len = strlen(string);
rev(string, 0, len);
for (int i=0; i<len;) {
int l = 0;
int j=i;
while (j<len && string[j]!=' ') ++j;
rev(string, i, j-i);
i=j+1;
}
}

The current logic reverses individual words from last to second word. However to reverse the first word you will have to add a check apart from
if(toReverse[i] == ' ')
as the first character need not be a space.
A separate check can be used when counter 'i' reaches zero, i.e. first character

Related

Reversing the order of words backwards in a string

Sorry for such a mediocre question, but I ran into what seems to be a tiny problem, but simply can't get over it. For my task I have to take a line of string from a file, and put it into another file backwards, for example:
one two three
four five six
would be
three two one
six five four
My problem is, is that I'm getting
three two one
si five four
So basically the flaw is that there is a space character at the beginning of each line and the last letter of the last word is always missing. Here's my reverse function:
void reverse(char input[], int length, char output[]) {
char space = 32;
input[length - 1] = space;
int value = 0;
int i, k = 0, j;
for (i = 0; i <= length; i++) {
if (input[i] == space) {
for (j = i - 1; j >= k; j--, value++) {
output[value] = input[j];
}
if (j == -1) {
output[value] = space;
value++;
}
k = i;
}
}
char c = 0;
for (int i = 0, j = length - 1; i <= j; i++, j--) {
c = output[i];
output[i] = output[j];
output[j] = c;
}
}
What I'm doing is first reversing each word by character, and then the whole line. If someone could help me find the last bits that I've missed I would greatly appreciate it.
The flaws come from your approach:
why do you force a space at offset length - 1? If you read the line with fgets(), there is probably a newline ('\n') at the end of the line, but it might be missing at the end of the input, which would explain the x getting overwritten on the last line.
you should not modify the input buffer.
Here is a simplified version, along with a simple main function:
#include <stdio.h>
#include <string.h>
void reverse(const char *input, int length, char *output) {
int i, j, k, v;
for (i = k = v = 0;; i++) {
if (i == length || input[i] == ' ') {
for (j = i; j-- > k; v++) {
output[v] = input[j];
}
for (; i < length && input[i] == ' '; i++) {
output[v++] = ' ';
}
if (i == length) {
output[v] = '\0';
break;
}
k = i;
}
}
for (i = 0, j = length - 1; i < j; i++, j--) {
char c = output[i];
output[i] = output[j];
output[j] = c;
}
}
int main() {
char input[256];
char output[256];
while (fgets(input, sizeof input, stdin)) {
reverse(input, strcspn(input, "\n"), output);
puts(output);
}
return 0;
}
Output:
three two one
six five four
Here is a simpler reverse function that operates in one pass:
#include <string.h>
void reverse(const char *input, int length, char *output) {
int i, j, k, v;
for (i = k = 0, v = length;; i++) {
if (i == length || input[i] == ' ') {
for (j = i; j-- > k;) {
output[--v] = input[j];
for (; i < length && input[i] == ' '; i++) {
output[--v] = ' ';
}
if (v == 0) {
output[length] = '\0';
break;
}
k = i;
}
}
}
Replace input[length - 1] = space; with input[length] = space;

String array prints out trash values

So I have an assignment where I should delete a character if it has duplicates in a string. Right now it does that but also prints out trash values at the end. Im not sure why it does that, so any help would be nice.
Also im not sure how I should print out the length of the new string.
This is my main.c file:
#include <stdio.h>
#include <string.h>
#include "functions.h"
int main() {
char string[256];
int length;
printf("Enter char array size of string(counting with backslash 0): \n");
/*
Example: The word aabc will get a size of 5.
a = 0
a = 1
b = 2
c = 3
/0 = 4
Total 5 slots to allocate */
scanf("%d", &length);
printf("Enter string you wish to remove duplicates from: \n");
for (int i = 0; i < length; i++)
{
scanf("%c", &string[i]);
}
deleteDuplicates(string, length);
//String output after removing duplicates. Prints out trash values!
for (int i = 0; i < length; i++) {
printf("%c", string[i]);
}
//Length of new string. The length is also wrong!
printf("\tLength: %d\n", length);
printf("\n\n");
getchar();
return 0;
}
The output from the printf("%c", string[i]); prints out trash values at the end of the string which is not correct.
The deleteDuplicates function looks like this in the functions.c file:
void deleteDuplicates(char string[], int length)
{
for (int i = 0; i < length; i++)
{
for (int j = i + 1; j < length;)
{
if (string[j] == string[i])
{
for (int k = j; k < length; k++)
{
string[k] = string[k + 1];
}
length--;
}
else
{
j++;
}
}
}
}
There is a more efficent and secure way to do the exercise:
#include <stdio.h>
#include <string.h>
void deleteDuplicates(char string[], int *length)
{
int p = 1; //current
int f = 0; //flag found
for (int i = 1; i < *length; i++)
{
f = 0;
for (int j = 0; j < i; j++)
{
if (string[j] == string[i])
{
f = 1;
break;
}
}
if (!f)
string[p++] = string[i];
}
string[p] = '\0';
*length = p;
}
int main() {
char aux[100] = "asdñkzzcvjhasdkljjh";
int l = strlen(aux);
deleteDuplicates(aux, &l);
printf("result: %s -> %d", aux, l);
}
You can see the results here:
http://codepad.org/wECjIonL
Or even a more refined way can be found here:
http://codepad.org/BXksElIG
Functions in C are pass by value by default, not pass by reference. So your deleteDuplicates function is not modifying the length in your main function. If you modify your function to pass by reference, your length will be modified.
Here's an example using your code.
The function call would be:
deleteDuplicates(string, &length);
The function would be:
void deleteDuplicates(char string[], int *length)
{
for (int i = 0; i < *length; i++)
{
for (int j = i + 1; j < *length;)
{
if (string[j] == string[i])
{
for (int k = j; k < *length; k++)
{
string[k] = string[k + 1];
}
*length--;
}
else
{
j++;
}
}
}
}
You can achieve an O(n) solution by hashing the characters in an array.
However, the other answers posted will help you solve your current problem in your code. I decided to show you a more efficient way to do this.
You can create a hash array like this:
int hashing[256] = {0};
Which sets all the values to be 0 in the array. Then you can check if the slot has a 0, which means that the character has not been visited. Everytime 0 is found, add the character to the string, and mark that slot as 1. This guarantees that no duplicate characters can be added, as they are only added if a 0 is found.
This is a common algorithm that is used everywhere, and it will help make your code more efficient.
Also it is better to use fgets for reading input from user, instead of scanf().
Here is some modified code I wrote a while ago which shows this idea of hashing:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define NUMCHAR 256
char *remove_dups(char *string);
int main(void) {
char string[NUMCHAR], temp;
char *result;
size_t len, i;
int ch;
printf("Enter char array size of string(counting with backslash 0): \n");
if (scanf("%zu", &len) != 1) {
printf("invalid length entered\n");
exit(EXIT_FAILURE);
}
ch = getchar();
while (ch != '\n' && ch != EOF);
if (len >= NUMCHAR) {
printf("Length specified is longer than buffer size of %d\n", NUMCHAR);
exit(EXIT_FAILURE);
}
printf("Enter string you wish to remove duplicates from: \n");
for (i = 0; i < len; i++) {
if (scanf("%c", &temp) != 1) {
printf("invalid character entered\n");
exit(EXIT_FAILURE);
}
if (isspace(temp)) {
break;
}
string[i] = temp;
}
string[i] = '\0';
printf("Original string: %s Length: %zu\n", string, strlen(string));
result = remove_dups(string);
printf("Duplicates removed: %s Length: %zu\n", result, strlen(result));
return 0;
}
char *remove_dups(char *str) {
int hash[NUMCHAR] = {0};
size_t count = 0, i;
char temp;
for (i = 0; str[i]; i++) {
temp = str[i];
if (hash[(unsigned char)temp] == 0) {
hash[(unsigned char)temp] = 1;
str[count++] = str[i];
}
}
str[count] = '\0';
return str;
}
Example input:
Enter char array size of string(counting with backslash 0):
20
Enter string you wish to remove duplicates from:
hellotherefriend
Output:
Original string: hellotherefriend Length: 16
Duplicates removed: helotrfind Length: 10

Caesar cipher printing out numbers instead of decrypted Text? in C

So I have this caesar cipher program, however when I run it it only prints out numbers instead of the decrypted text. Anyone know what I am missing? I believe there might be something wrong in the bool solved function.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "rotUtils.h"
bool solved( char decodearr[], char dictarr[][30], int size1, int size2){
char* compared;
bool result = false;
for(int j = 0; j < size2; j++){
compared = strstr( decodearr, dictarr[j]);
}
if( compared != '\0'){
result = true;
}
return result;
}
int decode( char codearr[], char dictarr[][30], int size1, int size2)
{
bool solution = false;
int key = -50;
char decodearr[10000];
while(solution == false && key < 51)
{
for( int i = 0; i < size1; i++)
{
if(!isspace(codearr[i]))
{
decodearr[i] = rotate(codearr[i], key);
}
else
decodearr[i] = codearr[i];
}
solution = solved( decodearr, dictarr, size1, size2);
if( solution == false)
{
key++;
}
}
for( int j = 0; j < size1; j++)
{
codearr[j] = decodearr[j];
}
return key;
}
int main( int argc, char* argv[])
{
char* file = argv[1];
char* dictionary = argv[2];
char code[10000];
char dict[30000][30];
FILE* codeFile;
codeFile = fopen(file, "r");
int i = 0;
int j = 0;
int key;
FILE* dictFile;
dictFile = fopen(dictionary, "r");
while(!feof(codeFile))
{
code[i] = fgetc(codeFile);
i++;
}
code[ i + 1] = '\0';
fclose(codeFile);
while(!feof(dictFile))
{
fscanf(dictFile, "%s", dict[j]);
j++;
}
key = decode(code, dict, i, j);
fclose(dictFile);
for(int k = 0; k < i; k++)
{
printf("%d", code[k]);
}
printf( "\nThe key is: %d\n", key);
return 0;
}
printf("%d", code[k]); means "print out the decimal digits that represent the integer code[k]".
If you want "print out the character that represents the integer code[k], then you'd want the %c format specifier instead: printf("%c", code[k]);
You only ever print numbers
printf("%d", code[k]);
perhaps try
printf("%c", code[k]);
which prints the character that number represents.
Just use "%c" instead of "%d" in your code when you want to print code[k].
Good luck!

Reverse Words in String

For some reason, I can't get this to work! Can anyone tell me where I've gone wrong? This is supposed to reverse the words in a give string (i.e from "this is a test" to "test a is this")
#include <stdio.h>
#include <stdlib.h>
char *reverse(char const *input)
{
char *ret = (char *)malloc(sizeof(char) * strlen(input));
int length = 0;
int numWords = 1;
int i;
for(i=0; input[i]!=NULL; i++)
{
length++;
if(input[i]==' ')
numWords++;
}
char words[numWords];
int currentWord = numWords;
for(i=0; input[i]!=NULL; i++)
{
if (input[i]==' '){
currentWord--;
}else{
words[currentWord] = words[currentWord] + input[i];
}
}
for(i=0; i < numWords; i++)
{
ret = ret + words[i];
}
return ret;
}
int main(int argc, char **argv)
{
int nTestcase = 0;
int i = 0;
char inputstr[100];
char *reversedStr = NULL;
scanf("%d\n", &nTestcase);
for (i = 0; i < nTestcase; i++)
{
fgets(inputstr, 100, stdin);
reversedStr = reverse(inputstr);
printf("%s\n", reversedStr);
free(reversedStr);
memset(inputstr, 0, 100);
}
return 0;
}
words[currentWord] = words[currentWord] + input[i];
You can't add characters to each other like that expecting string concatenation. And I imagine you expect words to be an array of words (i.e. strings), but its type is not that, words is just an array of characters.
Like #Tom said, you're doing this again in the last for loop:
ret = ret + words[i];
Joseph, unlike other programming languages ( c# or PHP ), string handling functions of C are quite basic.
You cannot add strings directly, however there are a host of library functions you can use to accomplish the same task.
Check out,
strtok - Use it to split the string to words. strtok reference
strncat - Use to concatenate strings
strings in C are just byte arrays terminated with the null character ( byte with value 0).
Here is shorter/cleaner way
private char[] reverseWords(char[] words) {
int j = words.length - 1;
for (int i = 0; i < (words.length)/2; i++) {
if(i==j)
continue;
char temp = words[i];
words[i] = words[j];
words[j]=temp;
j--;
}
int lastIndex = 0;
for (int i=0;i<words.length;i++){
if(words[i]==' '){
words = reverseWord(words,lastIndex,i-1);
lastIndex=i+1;
}
}
words = reverseWord(words,lastIndex,words.length-1);
return words;
}
private char[] reverseWord(char[] words, int from, int to) {
int j=to;
for(int i=from;i<((to/2)+from/2);i++){
if(i==j) continue;
char temp = words[j];
words[j]=words[i];
words[i]=temp;
j--;
}
return words;
}

how to perform reversing a sentence Word by Word in C?

#include <stdio.h>
int main(void)
{
int i,j;
int wordstart = -1;
int wordend = -1;
char words[]= "this is a test";
char temp;
// Reverse each word
for (i = 0; i < strlen(words); ++i)
{
wordstart = -1;
wordend = -1;
if(words[i] != ' ')
wordstart = i;
for (j = wordstart; j < strlen(words); ++j)
{
if(words[j] == ' ')
{
wordend = j - 1;
break;
}
}
if(wordend == -1)
wordend = strlen(words);
for (j = wordstart ; j <= (wordend - wordstart) / 2; ++j)
{
temp = words[j];
words[j] = words[wordend - (j - wordstart)];
words[wordend - (j - wordstart)] = temp;
}
i = wordend;
printf("reversed string is %s:", words);
}
}
I tried in this way but i am getting this output:
siht is a test
my expected output is:
test a is this
I would appreciate if some one could come with a different approach for which time complexity is very less or correct me if it is the right approach. Thanks
Perhaps this belongs on the code review site instead?
Your approach seems very efficient to me (except that I would only call strlen(words) once and save the result in a register).
Two possible bugs look like:
wordend = strlen(words);
should be
wordend = strlen(words)-1;
and
for(j = wordstart ; j <= (wordend - wordstart) / 2 ; ++j) {
should be
for(j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
Final code looks like (with some extra {}):
#include <stdio.h>
int main(int argc,char *argv[])
{
int i,j;
char words[]= "this is a test";
int L=strlen(words);
// Reverse each word
for(i = 0; i < L; ++i) {
int wordstart = -1;
int wordend = -1;
if(words[i] != ' ')
{
wordstart = i;
for(j = wordstart; j < L; ++j) {
if(words[j] == ' ') {
wordend = j - 1;
break;
}
}
if(wordend == -1)
wordend = L-1;
for(j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
char temp = words[j];
words[j] = words[wordend - (j - wordstart)];
words[wordend - (j - wordstart)] = temp;
}
i = wordend;
}
}
printf("reversed string is %s:",words);
return 0;
}
You can create a double linked list as a base data structure. Then, iterate through the words and insert them in the list as you find them.
When you reach the end of the sentence, simply traverse the list backwards and print the words as you go through them
Simply we can just use a n*1 2D character array tailored to suit our needs!!!
#include <stdlib.h>
int main()
{
char s[20][20];
int i=0, length=-1;
for(i=0;;i++)
{
scanf("%s",s[i]);
length++;
if(getchar()=='\n')
break;
}
for(i=length;i>=0;i--)
printf("%s ",s[i]);
return 0;
}
Start tokenizing the line from the last character and continue to the first character. Keep one pointer anchored at the base of the current word, and another pointed which will decrease while a word start is not found. When you find a word start while scanning like this, print from the word start pointer to the word end anchor. Update the word end anchor to the previous character of the current word start char.
You might want to skip the blankspace characters while scanning.
UPDATE
This is a quick implementation:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_BUF 256
void show_string (char *str, int i, int n)
{
while (i <= n)
{
printf ("%c", str[i]);
i++;
}
}
int main (void)
{
char str[MAX_BUF];
int end_anchor, start_ptr;
int state;
printf ("\nEnter a string: ");
scanf (" %[^\n]", str);
start_ptr = strlen (str) - 1;
end_anchor = start_ptr;
state = 0;
while (start_ptr >= -1)
{
switch (state)
{
case 0:
if ((!isspace (str[start_ptr]) && (start_ptr >= 0)))
{
start_ptr--;
}
else
{
state = 1;
}
break;
case 1:
show_string (str, start_ptr + 1, end_anchor);
state = 2;
start_ptr--;
printf (" ");
break;
case 2:
if (!isspace (str[start_ptr]))
{
state = 0;
end_anchor = start_ptr;
}
else
{
start_ptr--;
}
break;
}
}
printf ("\n");
return 0;
}
The end_anchor points to each end word, and the start_ptr finds the start of the word of which the end is held by end_anchor. When we find a word start (by blankspace characters or start_ptr = -1), we print all the characters from start_ptr + 1 to end_anchor. The + 1 is because of the implementation: start_ptr points to the blankspace character, and the print routine will print all the characters from i to n. Once we have detected one blank space we print it and we skip adjacent blankspaces (in case 2) and preserve only one which is manually printed. Once a non blankspace is detected, we have got another word end, for which we set the end_anchor to this index in the case 2, and set state = 0 , so that we can search for the word start again.
if(words[i] != ' ')
wordstart = i;
This statement what about the else part? if words[i] == ' ', and wordstart remains -1.
So maybe try to use:
while (words[i] && words[i] == ' ') ++i;
if (!words[i])
break;
wordstart = i;
Then you should output the result out of the i loop.
Finally, if you want to get the result you expected, you should reverse the whole sentence once more, with the way you used in the loop.
I would use write function similar to strrchr for finding last occurence of ' ', if its found print word that follows, rewrite this ' ' with '\0' and repeat it in loop till no more words are found. At the end I would print the content of this string again because there is most likely no ' ' before the first word.
I would write own function instead of strrchr because strrchr calculates the lenght of the given string, which is redundant in this case. This length doesn't have to be calculated more than once.
Here's the code:
char* findLastWord(char* str, int* len)
{
int i;
for (i = *len - 1; i >= 0; --i)
{
if (str[i] == ' ')
{
str[i] = '\0';
if (i < *len - 1)
{
*len = i - 1;
return &str[i + 1];
}
}
}
return NULL;
}
int main (int argc, char *argv[])
{
char str[] = " one two three four five six ";
int len = strlen(str);
char* lastWord = findLastWord(str, &len);
while (lastWord != NULL)
{
printf("%s\n", lastWord);
lastWord = findLastWord(str, &len);
}
if (len > 1)
printf("%s\n", str);
return 0;
}
output:
six
five
four
three
two
one
Hope this helps ;)
#include<stdio.h>
#include<string.h>
void reverse(char *str, size_t len)
{
char tmp;
size_t beg, end;
if (len <=1) return;
for (beg=0,end=len; beg < --end ; beg++) {
tmp = str[beg];
str[beg] = str[end];
str[end] = tmp;
}
}
int main(void)
{
char sentence[] = "one two three four five";
size_t pos, len;
printf("Before:%s\n",sentence);
for (pos = len= 0; sentence[pos]; pos += len) {
pos += strspn( sentence+pos, " \t\n" );
len = strcspn( sentence+pos, " \t\n" );
reverse ( sentence + pos, len );
}
reverse ( sentence , pos );
printf("After:%s\n",sentence);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
char* stringrev(char s[], int len)
{
char *s1 = (char*)malloc(len+1);
int i=0;
while (len>0)
{
s1[i++] = s[--len];
}
s1[i++] = '\0';
return s1;
}
void sentrev(char s[], int len)
{
int i=0; int j=0;
char *r = (char*)malloc(len+1);
while(1)
{
if(s[j] == ' ' || s[j] == '\0')
{
r = stringrev(s+i, j-i);
i = j+1;
cout<<r<<" ";
}
if (s[j] == '\0')
break;
j++;
}
}
int main()
{
char *s = "this is a test";
char *r = NULL;
int len = strlen(s);
cout<<len<<endl;
r = stringrev(s, len);
cout<<r<<endl;
sentrev(r, len);
return 0;
}
The above code snap reverse the sentence, using char *r
and printing cout<
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char st[50], rst[50];
printf("Enter the sentence...\n");
gets(st);
int len=strlen(st), p;
int j=-1,k;
p=len;
for(int i=(len-1); i>=0; i--)
{
//searching for space or beginning
if(st[i]==' ')
{
//reversing and storing each word except the first word
for(k=i+1;k<p;k++)
{
//printf("%c",st[k]);
rst[++j]=st[k];
}
j++;
rst[j]=' ';
printf("\n");
p=i;
}
else if(i==0)
{
//for first word
for(k=i;k<p;k++)
{
//printf("%c",st[k]);
rst[++j]=st[k];
}
}
}
printf("Now reversing the sentence...\n");
puts(rst);
return 0;
}
Use a main for loop to traverse till the end of the sentence:
Copy the letters in a string until you find a space.
now call add#beginning function and in that function add the string each time you pass a string to the linked list.
print the contents of the linked list with a space inbetween to get the expected output
My code,just traverse from the last and if you find a space print the characters before it,now change the end to space-1;This will print till the second word,finally just print the first word using a single for loop.Comment for alter approach.
Program:
#include<stdio.h>
int main()
{
char str[200];
int i,j,k;
scanf("%[^\n]s",&str);
for(i=0;str[i]!='\0';i++);
i=i-1;
for(j=i;j>=0;j--)
{
if((str[j])==' ')
{
for(k=j+1;k<=i;k++)
{
printf("%c",str[k]);
}
i=j-1;
printf(" ");
}
}
for(k=0;k<=i;k++)
{
printf("%c",str[k]);
}
}
using stack
#include <iostream>
#include <stdio.h>
#include <stack>
int main()
{
std::stack<string> st;
char *words= "this is a test";
char * temp = (char *)calloc(1, sizeof(*temp));
int size1= strlen(words);
int k2=0;
int k3=0;
for(int i=0;i<=size1;i++)
{
temp[k2] = words[i];
k2++;
if(words[i] == ' ')
{
k3++;
if(k3==1)
temp[k2-1]='\0';
temp[k2]='\0';
st.push(temp);
k2=0;
}
if(words[i] == '\0')
{
temp[k2]='\0';
st.push(temp);
k2=0;
break;
}
}
while (!st.empty())
{
printf("%s",st.top().c_str());
st.pop();
}

Resources