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.
Related
I'm trying to write a C program that only prints the last occurrence of repeating letters of a string. I have that part done but I want to store all those chars in a string. What I have so far is:
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
bool isLast(char *arg1, char ch, int p) {
p++;
while (arg1[p] != '\0') {
if ((arg1[p]) == ch) {
return false;
}
p++;
}
return true;
}
int main() {
char *word = "kaax";
char *vals = "1235";
char *result = "";
for (int i = 0; word[i] != '\0'; i++) {
if (isLast(word, word[i], i)) {
result += vals[i];
}
}
printf("%s", result);
}
I want:
printf("%s",result);
to print:
fxkav
Since that is the logical result of my program and what the output should be.
How to phrase it ... Not at all.
Your "empty string" is a string literal of size 1 (containing only '\0'. It cannot be changed and even lesss extended.
If you need to manipulate "strings" (which in C is not really an existing concept) you need to represent them as sequences of characters, which are stored in a data structure which allows to change the contained characters and, in your case, also has space for more characters.
In cases where you can determine a maximum size (MAXSIZE) you could define an array of characters of that size like this
char SizedCharArray[MAXSIZE];
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;
}
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;
}
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.
I was practicing some programming problems and tried to code the popular "reverse words in a string" problem.
I tried to come up with my own code in C. I am able to partially get it right. That is, "hello world" becomes "world olleh". I am wondering what the bug is here. I think somewhere I am creating an off by 1 bug.
As much as possible, I wanted to do it without using library functions. I searched here for this problem & found many solutions, but I'd like to know why my solution doesn't work.
Here is the code:
#include <stdio.h>
#include <string.h>
void reverse(char*, int);
int main(int argc, char **argv)
{
char st[]= "hello world";
int len = strlen(st);
int i=0,j=0;
reverse(st,len-1); // Reverse the entire string. hello world => dlrow olleh
while(st[j]){ //Loop till end of the string
if ( *(st+j) == ' ' || *(st+j) == '\0' ) { //if you hit a blank space or the end of the string
reverse(st+i,j-1); // reverse the string starting at position i till position before the blank space i.e j-1
i=++j; //new i & j are 1 position to the right of old j
}
else {
j++; //if a chacacter is found, move to next position
}
}
printf("%s",st);
return 0;
}
void reverse(char *s, int n)
{
char *end = s+n; //end is a pointer to an address which is n addresses from the starting address
char tmp;
while (end>s) //perform swap
{
tmp = *end;
*end = *s;
*s = tmp;
end--;
s++;
}
}
Thank you!
UPDATE: Based on #Daniel Fischer's answer, here is the correct implementation : http://ideone.com/TYw1k
The problem is that
while(st[j]){ //Loop till end of the string
if ( *(st+j) == ' ' || *(st+j) == '\0' )
the while condition prevents the loop being entered at the end of the string, so the last word doesn't get reversed again.
You can either make it an infinite loop, and add an
if (st[j] == '\0') break;
after the reversing, or reverse the last word after the while loop was left.
You have an off by one error indeed: the call
reverse(st+i,j-1);
should be
reverse(st+i,j-i-1);
Your code passes j-1 which is the length from the beginning of the string to the position of the last space; it should be the length of the last word, so you need to subtract the index of the first character (i.e. i).
You are also not reversing the last word (see the other answer for the details on that).
I think that you want to reverse words in a string, not reverse the whole string and then rereverse single words. So, delete first reverse and then apply suggested changes above.
#include <stdio.h>
#include <string.h>
void reverse(char*, int);
int main(int argc, char **argv)
{
char st[]= "hello world";
int i=0, j=0;
while(st[j]){ //Loop till end of the string
if ( st[j] == ' ') { //if you hit a blank space or the end of the string
reverse(&st[i], j - i - 1); // reverse the string starting at position i till position before the blank space i.e j-1
i = ++j; //new i & j are 1 position to the right of old j
}
else {
j++; //if a chacacter is found, move to next position
}
}
reverse(&st[i], j - i - 1);
printf("%s\n",st);
return 0;
}
void reverse(char *s, int n)
{
char *end = s + n; //end is a pointer to an address which is n addresses from the starting address
char tmp;
while (end > s) //perform swap
{
tmp = *end;
*end = *s;
*s = tmp;
end--;
s++;
}
}
Take care when input string would be '\0' or something like ' Hello world'. Above code doesn't managed this kind of situations. Think about it!
#RBK: You first take a string, reverse it, then based on specific words you again reverse them.
I followed a slightly different approach of doing this. I take the string then reverse if required otherwise i copy the same word as it is.
int main(int argc, char*argv[])
{
char *p,st[]= "hello world";
char buf[12]={0};
char fstr[12]={0};
int i=0,j=0,k=0,l=0;
for(p=st;*p!='\0';p++){
//Get the Word
buf[i++] = *p;
//Parse the Word
if(*p == ' ' || *(p+1) == '\0'){
buf[i]='\0';
j=i-1;
i=0; //reset counter
if(k){ //reverse word and copy
while(j>=i){
fstr[l++]=buf[j--];
}
k=0;
}
else{ //copy same word
while(i<=j){
fstr[l++]=buf[i++];
}
i=0; //reset counter
k=1;
}
}
}
fstr[l]='\0';
printf("%s\n",fstr);
return 0;
}