Print words in string in reverse order C - c

I take user input using fgets() and store it into a temp array. I then concatenate that to a main array called userInput so that the user can enter multiple lines.
Let's say the user enters the following:
This is a sentence
This is a new line
I need it to print each line in the order they were entered but reverse the order of words like below:
sentence a is This
line new a is This
I have the current approach but I get this:
line
new a is sentence
This a is This
Below is my code where I call reversePrint() with a string to reverse:
void printToSpace(const char *str) {
do {
putc(*str, stdout);
} while(*str++ != ' ');
}
void reversePrint(const char *str) {
const char *p = strchr(str, ' ');
if (p == NULL) {
printf("%s", str);
}
else {
reversePrint(p + 1);
printToSpace(str);
}
}

Here is an alternative way:
#include <stdio.h>
#include <string.h>
void reversePrint(const char *str)
{
if (str)
{
reversePrint(strtok (NULL, " \t\n\r"));
printf("%s ", str);
}
}
int main(void)
{
char string[] = "This is a sentence";
reversePrint(strtok(string, " \t\n\r"));
return 0;
}
It seems so clear and simple that I suspect if strtok() is born for requirements like this.

Here are just a few thoughts...
I feel that using fgets will provide you with an undesired new-line marker. Hence, you need to handle the "\r\n" in the reverse printing function.
I feel that the reverse printing is easier to perform in a single function, although I loved the recursive approach, so I'll use it here.
I should point out that I wouldn't use a recursive function if this was a production application, as we'll be wasting resources and bloating the stack for no good reason.
On a non-recursive approach I would probably use the %.*s format, instead of printing each char separately.
I think your code would work if you only changed printToSpace so that it manages the \n contingency - but I felt like re-writinfg the function. Try this in your solution:
void printToSpace(const char *str) {
do {
putc(*str, stdout);
} while(*str && *str != '\n' && *str != '\r' && *str++ != ' ');
}
Here's my full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_rev(char* str);
// collects two strings and send them to the `print_rev` function
int main(int argc, char const* argv[]) {
char str_array[2][255];
// Get string 1
printf("Enter the first string (up to 255 characters):\n");
fgets(str_array[0], 255, stdin);
printf("Please enter the second string (up to 255 characters):\n");
fgets(str_array[1], 255, stdin);
printf("You entered:\n1. %s2. %s", str_array[0], str_array[1]);
printf("\nString 1 reversed: ");
print_rev(str_array[0]);
printf("\nString 2 reversed: ");
print_rev(str_array[1]);
printf("\n");
}
// prints a string in reverse order.
void print_rev(char* str) {
// find the first occurrence of the ` ` (space)
char* p = strchr(str, ' ');
// if a space exists...
if (p) {
// call `print_rev` for whatever's after the space.
print_rev(p + 1);
// print a space
putc(' ', stdout);
}
// print every character until an EOL, space or NULL is encountered
while (*str && *str != ' ' && *str != '\n' && *str != '\r')
putc(*(str++), stdout);
}

#include <stdio.h>
#include <string.h>
#define MAX_LEN 100000
int main()
{
char str[MAX_LEN], temp[MAX_LEN];
printf("Enter the Sentence to print reverse : ");
scanf("%[^\n]%*c", &str);
int i, left, right, length = strlen(str);
left = 0;
right = length - 1;
printf("%d \n", length);
for(i=0;i<length;i++)
{
temp[i] = str[right];
right--;
}
printf("%s",temp);
return 0;
}

Related

Finding a reversed words in a given string using C program

Actually I have been searching for more than 1 week to find a solution for finding a reversed words in a given string using C. My question is, I have been given a string like this "bakelovekac". Here I have a reversed word of "ake" as "eka" in a string. Now I need to find out this reversed word in a given string and print it. How can it be done? Thanks in advance!
A basic approach would be to iterate over all the characters of the string and for each character check if it is being repeated, if yes then check for the presence of a possible reverse string.
A crude code for above approach would look something like this:
#include <stdio.h>
void checkForRevWord(char *str, char *rev){
int length = 0;
while(1){
if(str >= rev)
break;
if(*str != *rev)
break;
length++;
str++;
rev--;
}
if(length > 1){
while(length--)
printf("%c", *(rev+length+1));
printf("\n");
}
return;
}
int main()
{
char *inputStr = "bakelovekac";
char *cur = inputStr;
char *tmp;
while(*cur != '\0'){
tmp = cur+1;
/* find if current char gets repeated in the input string*/
while(*tmp != '\0'){
if(*tmp == *cur){
checkForRevWord(cur, tmp);
}
tmp++;
}
cur++;
}
}
Go through this program
#include <stdio.h>
#include <string.h>
int main()
{
char text[50]; //this character array to store string
int len,i;
printf("Enter a text\n");
scanf("%[^\n]s",text);//getting the user input with spaces until the end of the line
len=strlen(text);//getting the length of the array and assigning it the len variable
for(i=len-1;i>=0;i--)
{
printf("%c",text[i]); //printing the text from backwards
}
return 0;
}
thank you.

Reversing a string in C using Visual Studio

I'm building a program for reversing a string in visual studio, and while I run the code and enter a word I want to reverse, the program crashes.
#include <stdio.h>
#include <conio.h>
#include <string.h>
main(void) {
char r[256];
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(" %s", r, sizeof(r));
d = strlen(r);
for (i=d;i!=0;i--) {
printf("%s",i);
}
return 0;
}
Please note that I tried your program on Linux, so no MS Visual C++ and more specifically no conio.h and gets_s.
There are multiple problems with your program:
Your call to gets_s is incorrect, according to this and this, gets_s is defined as:
char *gets_s(
char *buffer,
size_t sizeInCharacters
);
You are calling it with illegal arguments. Instead of gets_s(" %s", r, sizeof(r)); you need to call it like this:
gets_s(r, 256);
the first parameter is pointer to the string buffer where the gets_s function will store the line from input and the second is the size of the buffer, note that in char r[256] you can store 255 characters and terminating zero (\0).
Your for loop is incorrect instead of for (i=d;i!=0;i--) { you need to do it like this:
for (i=d-1;i>=0;i--) {
now the loop starts from last character instead of \0 and ends when the i < 0 ie. the last print will be when i=0.
And your final mistake is that you are using printf incorrectly instead of printf("%s",i); you need to do:
printf("%c",r[i]);
because you are printing characters: "%c" is for char output and r[i] is i-th character from string r (don't forget that we count from 0).
So, in total this is how the program should look like:
#include <stdio.h>
#include <conio.h> // does not exist on GCC (Linux)
#include <string.h>
main(void) {
char r[256]; // 255 characters + \0
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(r, 256); // store at most 255 characters + \0
// does not work on GCC (Linux) even with -std=C11
d = strlen(r);
// start from last character and include first
for (i=d-1;i>=0;i--) {
// %c - character, r[i] gets the i-th character from string r
printf("%c",r[i]);
}
return 0;
}
void rev(char *s)
{
char *start, *end;
end = start + strlen(s) - 1;
for (start = s; end > start; ++start, --end) {
char tmp;
tmp = *start;
*start = *end;
*end = tmp;
}
}
Use the fgets function, and also put the reversing code in its own function, like I did. So the final code is
int main()
{
char line[80];
fgets(line, 80, stdin);
/* don't allow empty string */
if (*line == '\0') {
fprintf(stderr, "Empty string is not a string\n");
return 1;
}
/* remove the \n placed by fgets */
remnl(line);
rev(line);
printf("%s\n", line);
return 0;
}
void remnl(char *s) { s[strlen(s) - 1] = 0; }
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(void) {
char r[256];
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(r, sizeof(r));
d = strlen(r) - 1;
for (i = d; i >= 0; i--) {
printf("%c", r[i]);
}
_getch();
return 0;
}

C Caesar Cipher error random string output

So I have been taking classes on C and one of the exercises was to program a caesar cipher program that both encrypts and decrypts. And when the input is "ab cd", the output should be "de#fg" but instead it outputs "de?g?". So my guess is the spacebar messes everything up. But also another error was found when I inputted "a" and it outputted "d?ad?". Thanks in advance.
#include <stdio.h>
#include <string.h>
void cipher(char plain_str[], char cipher_str[]);
void decipher(char cipher_str[], char decipher_str[]);
int main() {
char plain_str[30];
char cipher_str[30];
char decipher_str[30];
printf("Enter plain string: ");
scanf("%s", plain_str);
cipher(plain_str, cipher_str);
decipher(cipher_str, decipher_str);
}
void cipher(char plain_str[], char cipher_str[]) {
int i = 0;
while(plain_str[i] != '\0') {
if((plain_str[i]+3) >= 0 && (plain_str[i]+3) <= 127) {
cipher_str[i] = plain_str[i] + 3;
} else {
cipher_str[i] = plain_str[i] - 124;
}
i++;
}
printf("%s\n", cipher_str);
}
void decipher(char cipher_str[], char decipher_str[]) {
//asdf
}
The %s operator in scanf only reads a single word, not a whole line. So if you enter ab cd, only ab is put into plain_str. To read a whole line, use fgets():
fgets(plain_str, sizeof(plain_str), stdin);
size_t len = strlen(plain_str);
if (plain_str[len-1] == '\n') {
plain_str[len-1] = '\0'; // Remove newline
}
The other problem is that you're never adding the null terminator to cipher_str, so you're printing whatever garbage is in it after the encoded characters. The simplest way to resolve this is to initialize it to an all-zero array when you declare the variable:
char cipher_str[30] = {0};

Removing Characters of a String

I'm trying to write a code that asks the user to enter a string and takes of all characters except the alphabetical.
Now i did it myself and it doesn't seem to work properly. I'm new to strings so i'm trying to understand and master strings. I tried to use gdb on mac but i don't have all the functions to understand this.
Could you please help?
What the code must do: User inputs (for example): h**#el(l)o&^w
and the output is hello.
here is my code:
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
int i;
int seen = 0;
printf("Enter String: ");
scanf("%s", string);
for (i=0; string[i]!='\0'; i++)
{
if (((string[i]<='a' || string[i]>'z')&&(string[i]<='A' || string[i]>'Z')) ||string[i]!='\0')
{
seen = 1;
}
else
seen = 0;
}
if (seen==0)
{
printf("%s", string);
}
}
well, your code has a couple of important problems:
you're not checking boundaries when iterating… what if I type in a 101 characters string? and a 4242 characters string?
next problem, is that scanf("%s", …) is considered dangerous, for the same reasons
so basically, what you'd want is to use fgets() instead of scanf().
But why not just get the input character by character, and build a string that has only the chars you want? It's simpler and flexible!
basically:
#include <ctype.h>
int main() {
char* string[100];
int i=0;
printf("Enter your string: ");
do {
// getting a character
char c = getchar();
// if the character is alpha
if (isalpha(c) != 0)
// we place the character to the current position and then increment the index
string[i++] = c;
// otherwise if c is a carriage return
else if (c == '\r') {
c = getchar(); // get rid of \n
// we end the string
string[i] = '\0'
}else if (c == '\n')
// we end the string
string[i] = '\0';
// while c is not a carriage return or i is not out of boundaries
} while (c != '\n' || i < 100);
// if we've got to the boundary, replace last character with end of string
if (i == 100)
string[i] = '\0';
// print out!
printf("Here's your stripped string: %s\n", string);
return 0;
}
I did not run it on my computer because it's getting late, so my apologies in case of mistakes.
Addendum:
wee the program skips my statement and shuts down
that's because your condition is inversed, and remove the \0 condition, as it will always happen with the scanf() that always append \0 to the string to end it. Try exchanging seen = 1 and seen = 0 or try using the following condition:
if ((string[i]>='a' && string[i]<='z')||(string[i]>='A' && string[i]<='Z')))
seen = 1;
else
seen = 0;
or simply, use ctypes's isalpha() function, like in our two examples!
No part(remove the extra characters) to change the string in your code.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char *filter(char *string, int (*test)(int)) {
char *from, *to;
for(to = from = string;*from;++from){
if(test(*from))
*to++ = *from;
}
*to = '\0';
return string;
}
int main(){
char string[100];
printf("Enter String: ");
scanf("%99s", string);
printf("%s\n", filter(string, isalpha));
return 0;
}

Storing separated strings

So I'm trying to write this program that takes a string, seperates the strings into words and puts the seperated words into a format like "word1+word2+word3..."
I've written a C program that gets a string and seperates the string into words. But I'm a little confused on how to keep each individual word and then place it in the above format.
Here is my code so far
#include <stdio.h>
#include <string.h>
int main()
{
int wordCount = 0;
char realString[200];
char testString[200];
char * nextWordPtr;
printf("Input string\n");
gets(realString);
strcpy(testString,realString);
nextWordPtr = strtok(testString," "); // split using space as divider
while (nextWordPtr != NULL) {
printf("word%d %s\n",wordCount,nextWordPtr);
wordCount++;
nextWordPtr = strtok(NULL," ");
}
}
Does anyone have any suggestions?
I don't understand really what you want? if you just want to output the string like this : 'word0+word1+...etc', you can use this code to accomplish this:
#include <stdio.h>
#include <stdlib.h>
#define INPUT_STRING_LEN 128
int main(int argc, char **argv)
{
char input_string[INPUT_STRING_LEN];
char *out_string;
int index;
/* Get user input */
fgets(input_string, INPUT_STRING_LEN, stdin);
out_string = (char *) malloc((INPUT_STRING_LEN + 1) * sizeof(char));
/* Loop through input string and replace space with '+' */
index = 0;
while (input_string[index] != '\0')
{
if (input_string[index] == ' ')
out_string[index] = '+';
else
out_string[index] = input_string[index];
index++;
}
/* We got this out string */
fprintf(stdout, "We got this out string :\n--->\n%s<---\n", out_string);
/* Free the allocated memory */
free(out_string);
return 0;
}
If you want something else please edit the question.

Resources