I've been trying to solve this exercise for a week now and my code doesn't work and I can't understand why and how to change it. The exercise is: recieving a length from the user, then recieving a string (str) as long as 'length' and then recieving a number (int n) from the user.Then I need to execute the function 'void ReverseNumWords (char*str, int n).The function reverses the first n words in the string. For example: for 'I am your father StarWars' and n=3: 'your am I father StarWars'. It'll be right to assume that the words are separated by ' '. Thanks for the help!!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
void Reverse()
{
int len,num;
char *str;
printf("Please enter how many chars to allocate:\n");
//Asking from the user the length of a string.
scanf("%d", &len);
//Allocating memory for the string.
str = (char*)calloc(len, sizeof(int));
//Making sure the allocation was successful.
if (!str)
printf("Error: Cannot allocate Memory\n");
printf("Allocated %d chars\n", len);
printf("Please enter your string:\n");
scanf("%s", str);
printf("Please enter how many words to reverse:\n");
scanf("%d", &num);
ReverseNumWords(*str, num, len);
free(str);
}
void ReverseNumWords(char*str, int num,int len)
{
char *sub;
char temp;
//Allocating memory for the string.
sub = (char*)calloc(len, sizeof(int));
//Making sure the allocation was successful.
if (!sub)
printf("Error: Cannot allocate Memory\n");
int i, j,l;
i = j = 0;
for (; i < len, j <= num; i++)
if (str[i] == '\0' || str[i] == 0)
j++;
for (l = 0; l < i; l++)
sub[i] = str[i];
for (j = 0; j < i; j++)
temp = sub[j];
sub[j] = sub[i - (1+j)];
sub[i - (1+j)] = sub[j];
reverseWords(*sub);
}
void reverseWords(char *sub)
{
char *word_begin = sub;
char *temp = sub;
while (*temp)
{
temp++;
if (*temp == '\0')
{
reverse(word_begin, temp - 1);
}
else if (*temp == ' ')
{
reverse(word_begin, temp - 1);
word_begin = temp + 1;
}
}
reverse(sub, temp - 1);
}
void reverse(char *begin, char*sub, char *end)
{
char temp;
while (begin < end)
{
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
printf("%s\n", sub);
}