strings to arrays then print in c - c

I am trying to take a user inputted string and look at each code to see if it appears in another string of strings. So far my code works.
If the word is successfully found then the alpha representation is to be added to an array that will eventually be printed, but only if all codes were found.
I am having issues with what gets stored in my array that is going to be printed.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef char *string;
typedef char *alpha;
int main(void)
{
string morse[4]={".-", "-...","----.", ".."};
string alpha[4]={"A", "B", "9", "I"};
char prntArr[50];
char *input;
char *hold;
input = malloc(200);
hold = malloc(50);
int i=0;
int j=0;
int ret;
int x;
int w=0;
int z=0;
printf("please enter a string\n");
scanf("%[^\n]",input);
do{
if (input[i] !=' ')
{
hold[j] = input[i];
j++;
}
else
{
hold[j]='\0';
for (x=0;x<4;x++)
{
printf("value of x %d\n",x);
ret = strcmp(morse[x], hold);
if (ret==0)
{
printf("%s\n",alpha[x]);
prntArr[w]=*hold;
w++;
x=4;
}
else
{
ret=1;
printf("invalid Morse code!");
}
}
j = 0;
}
i++;
}while(input[i] !='\0');
for (z=0;z<50;z++)
{
printf("%c",prntArr[z]);
}
return 0;
free(input);
}

The problem you asked about is caused by the way prntArr is used in the program. It really should be an array of character pointers into the alpha array. Instead, it's manipulated as an array of characters into which the first character of each morse code element is stored. And when it's printed, the variable that tracks how much of the array is used is simply ignored.
Another problem is that your code uses spaces to break the codes but there won't necessarily be a space at the end of the line so a code might get missed. In the program below, I switched out scanf() for fgets() which leaves a newline character on the end of the input which we can use, like space, to indicate the end of a code.
Other problems: you print the invalid Morse code message at the wrong point in the code and you print it to stdout instead of stderr; you remember to free input but forget to free hold; you put code after return that never gets called.
Below is a rework of your code that addresses the above problems along with some style issues:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main(void)
{
char *morse[] = {".-", "-...", "----.", ".."};
char *alpha[] = {"A" , "B" , "9" , "I" };
char *print_array[50];
int print_array_index = 0;
char hold[50];
int hold_index = 0;
char input[200];
int i = 0;
printf("please enter a string: ");
fgets(input, sizeof(input), stdin);
while (input[i] !='\0') {
if (input[i] ==' ' || input[i] == '\n')
{
hold[hold_index] = '\0';
bool found = false;
for (int x = 0; x < sizeof(morse) / sizeof(char *); x++)
{
if (strcmp(morse[x], hold) == 0)
{
print_array[print_array_index++] = alpha[x];
found = true;
break;
}
}
if (!found)
{
fprintf(stderr, "invalid Morse code: %s\n", hold);
}
hold_index = 0;
}
else
{
hold[hold_index++] = input[i];
}
i++;
}
for (int x = 0; x < print_array_index; x++)
{
printf("%s ", print_array[x]);
}
printf("\n");
return 0;
}
SAMPLE RUNS
> ./a.out
please enter a string: ----. -... .- ..
9 B A I
>
> ./a.out
please enter a string: .- --- ..
invalid Morse code: ---
A I
>

Related

C Program to Check for Palindrome String

I wrote two sample programs to check for a palindrome string. But in both I am getting output like, its not a palindrome number. What I am missing?
I strictly assume somehow code is executing my if statement and put flag in to 1. May be because of that length calculation. Anyone has a better idea?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
int main(void) {
setbuf(stdout,NULL);
char name[100];
int i,length,flag=0,k;
printf("Enter your name");
/*scanf("%s",name);*/
gets(name);
length=strlen(name);
for(i=0;i<=length-1;i++)
{
for(k=length-1;k>=0;k--)
{
if(name[i]!=name[k])
{
flag=1;
break;
}
}
}
if(flag==0)
{
printf("Give word is a palindrome");
}
if(flag==1)
{
printf("This is NOT a palindrome word");
}
return 0;
}
and
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
int main(void) {
setbuf(stdout,NULL);
char name[100];
int i,length,flag=0;
printf("Enter your name");
/*scanf("%s",name);*/
gets(name);
length=strlen(name);
for(i=0;i<=length/2;i++)
{
if(name[i]!=name[length-1])
{
flag=1;
}
}
if(flag==0)
{
printf("Give word is a palindrome");
}
if(flag==1)
{
printf("This is NOT a palindrome word");
}
return 0;
}
First Algorithm
The algorithm you are using in the first program involves comparing each letter to every other letter which does not help in determining if the number is a palindrome and it does not seem fixable.
Second Algorithm
The problem with the second approach, however, is you are always comparing name[i] to name[length]. Instead change it to length-i-1. This will start comparing from length-1 and decrement the length of the character by 1 for every next iteration:
for(i = 0;i <= length / 2;i++)
{
if(name[i] != name[length-i-1])
{
flag=1;
break;
}
}
gets() and buffer overflow
Do not use gets. This method is susceptible to a buffer overflow. If you enter a string longer than 100 characters, it will result in undefined behavior. Use fgets instead for deterministic behavior:
fgets(name, sizeof(name), stdin);
This takes in the size of the buffer and only reads up to sizeof(name) characters.
Full code
Ideally, you should consider wrapping the logic to check if the string is a palindrome in a function:
int is_palindrome(char*);
int main(void)
{
char name[100];
setbuf(stdout,NULL);
printf("Enter your name");
fgets(name, sizeof(name), stdin);
if(is_palindrome(name))
{
printf("The given word is a palindrome");
}
else
{
printf("This is NOT a palindrome word");
}
return 0;
}
int is_palindrome(char* name)
{
int length = strlen(name);
int flag = 0, i;
for(i = 0;i <= length / 2; i++)
{
if(name[i]!=name[length-i-1])
{
return 0;
}
}
return 1;
}
There is plenty wrong with both your attempts. I strongly suggest using a debugger to investigate how your code works (or doesn't).
Your first attempt performs length2 (incorrect) comparisons, when clearly only length / 2 comparisons are required. The second performs length / 2 comparisons but the comparison is incorrect:
name[i] != name[length-1] ;
should be:
name[i] != name[length - i - 1] ;
Finally you iterate exhaustively when you could terminate the comparison as soon as you know they are not palindromic (on first mismatch).
There may be other errors - to be honest I did not look further than the obvious, because there is a better solution.
Suggest:
#include <stdbool.h>
#include <string.h>
bool isPalindrome( const char* str )
{
bool is_palindrome = true ;
size_t rev = strlen( str ) - 1 ;
size_t fwd = 0 ;
while( is_palindrome && fwd < rev )
{
is_palindrome = (str[fwd] == str[rev]) ;
fwd++ ;
rev-- ;
}
return is_palindrome ;
}
In use:
int main()
{
const char* test[] = { "xyyx", "xyayx", "xyxy", "xyaxy" } ;
for( size_t t = 0; t < sizeof(test)/sizeof(*test); t++ )
{
printf("%s : %s palindrome\n", test[t],
isPalindrome( test[t] ) ? "Is" : "Is not" ) ;
}
return 0;
}
Output:
xyyx : Is palindrome
xyayx : Is palindrome
xyxy : Is not palindrome
xyaxy : Is not palindrome
Try this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char text[100];
int begin, middle, end, length = 0;
printf("enter the name: ");
scanf("%s",text);
while ( text[length] != '\0' ){
length++;}
end = length - 1;
middle = length/2;
for ( begin = 0 ; begin < middle ; begin++ ) {
if ( text[begin] != text[end] ) {
printf("Not a palindrome.\n");
break;
}
end--;
}
if( begin == middle )
printf("Palindrome.\n");
return 0;
}
The problem with the first piece of code is you are comparing it more than required, compare it with length-i-1.
The main problem with the second code is you are comparing it with only the last letter of a word.
Hope you understood your mistake

I am writing a code about replacing a word in a string with another word and removing repeats. Cannot finish it but got half to work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
//This function converts a string to a sentence.
void
StrtoSent(char *string)
{
int length = 0,n = 0;
length = strlen(string);
for(n = 0; n < length; n++){
if((n ==0) && (string[n] >= 'b' && string[n] <= 'y')){
string[n] = string[n] - 32;
}
else if(string[n] == '.'){
if(string[n + 1] == ' '){
if(string[n+2]>= 'b' && string[n+2]<= 'y'){
string[n+2]= string[n+1] - 32;
}
}
}
}
}
int
main(void)
{
char string[50] = {0};
int length = 0,n = 0,a = 0,d = 0;
printf("\n\nEnter a wordstring Neo: ");
gets(string);
StrtoSent(string);//Here,we send the string off to the function
char str[] = "The xitraM is acutally the Matrix!";
char j[] = "xitraM";
char e[] = "Matrix";
char *result = NULL;
printf("Original string: %s\n",str);
printf("The converted sentence: %s",string);
char input[200];
getchar();
fflush(stdin);
fgets(input,200,stdin);
char c;
if (isdigit(c)) {
int n = c - '0'; //'0'-'9' -> 0 - 9
printf("%c is coverted to %d\n",c,n);
}
while((c=getchar()) != EOF) {
if(islower(c))
printf("%c will be converted to %c\n",c,toupper(c));
if(isupper(c))
printf("%c in lowercase is %c\n",c,tolower(c));
getchar();
}
}
How do I replace the word xitraM and get it to be like this output:
The xirtaM is actually the MATRIX!
Converted sentence:
The Matrix is actually the MATRIX!
Original:
a blACk cAT is in the xirtaM.
Converted sentence:
A Black Cat is in the Matrix.
My code allows you
so far to enter a wordstring and it will return a string, and it will
fix the //code if there are capitals in the wrong place and if the
punctuation is wrong, but I cannot seem to get the code to replace
xitraM with Matrix and I am stuck on that.
Some help would be great -- thanks!
This is prefaced by my top comments.
There are many issues with the code.
Never use gets--the man page for it says to not use it [and why].
Your main is reading a line but not doing much with it.
The loop at the bottom doing getchar makes no sense because you've already read the line with the fgets above. It looks like you're trying to preview the capitalization.
For the word substitution, use two buffers. An input and a separate output buffer. Although xirtaM and Matrix are the same length, using separate buffers allows the length of the strings to differ (i.e. it's more general).
You can loop through the input using strstr to find the "bad" string. Then, copy over the partial string that precedes it. Skip the bad string in the input. Then, copy over the "good" string to the output.
Your capitalization function makes no sense [and appears to do nothing].
Also, converting the "black cat" string, from your example isn't general because it would need to special case "cat" to produce "Cat". For English, "cat" is not a proper name, so it should be all lowercase.
Unfortunately, your code needed some heavy refactoring in order to work.
I had to change the capitalization function to just capitalize the first char of the first word of each sentence as that was the only thing that made sense to me [adjust to suit your needs].
I wired in your two test cases. And, I've added some debug printf statements.
Anyway, here's the code. I've annotated it, so that the part you had an issue with [the word substitution] should give you some ideas.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
//This function converts a string to a sentence.
void
StrtoSent(char *string)
{
int length = 0,n = 0;
length = strlen(string);
for(n = 0; n < length; n++){
if((n ==0) && (string[n] >= 'b' && string[n] <= 'y')){
string[n] = string[n] - 32;
}
else if(string[n] == '.'){
if(string[n + 1] == ' '){
if(string[n+2]>= 'b' && string[n+2]<= 'y'){
string[n+2]= string[n+1] - 32;
}
}
}
}
}
// fixcap -- capitalize sentences in the string
void
fixcap(char *string)
{
int capflg = 1;
while (1) {
int chr = *string;
// end of string
if (chr == 0)
break;
switch (chr) {
case ' ':
break;
case '.': // end of sentence -- restart capitalization
case '!':
capflg = 1;
break;
default:
// capitalize the [first letter of the] first word of a sentence
if (capflg) {
chr = toupper((unsigned char) chr);
capflg = 0;
}
else
chr = tolower((unsigned char) chr);
break;
}
*string++ = chr;
}
}
// fixword -- substitute word in string
void
fixword(char *out,const char *inp,const char *bad,const char *good)
{
int lenbad = strlen(bad);
int lengood = strlen(good);
char *cp;
int lencpy;
while (1) {
// find the "bad" string in the input
cp = strcasestr(inp,bad);
// the remaining input string is good -- copy it
if (cp == NULL) {
strcpy(out,inp);
break;
}
// get the length of the string leading up to the "bad" string
// copy it over and advance the pointers
lencpy = cp - inp;
memcpy(out,inp,lencpy);
inp += lencpy;
out += lencpy;
// skip over the bad string in the input
inp += lenbad;
// copy over the "good" string and advance the output pointer
strcpy(out,good);
out += lengood;
}
}
// fixall -- perform all actions
void
fixall(const char *string)
{
char inp[1000];
char out[1000];
strcpy(inp,string);
printf("DEBUG: BEFORE '%s'\n",inp);
//Here,we send the string off to the function
#if 0
StrtoSent(inp);
printf("DEBUG: AFTCAP '%s'\n",inp);
#endif
#if 1
fixcap(inp);
printf("DEBUG: AFTCAP '%s'\n",inp);
#endif
fixword(out,inp,"xirtaM","Matrix");
printf("DEBUG: AFTFIX '%s'\n",out);
}
// doline -- read and process an input line
int
doline(void)
{
char *cp;
char string[1000];
int more;
do {
printf("\n\nEnter a wordstring Neo: ");
cp = fgets(string,sizeof(string),stdin);
more = (cp != NULL);
if (! more)
break;
// strip newline
cp = strchr(string,'\n');
if (cp != NULL)
*cp = 0;
fixall(string);
} while (0);
return more;
}
int
main(void)
{
#if 0
char string[50] = {0};
int length = 0,n = 0,a = 0,d = 0;
#endif
// default test cases
fixall("The xirtaM is acutally the Matrix!");
fixall("a blACk cAT is in the xirtaM.");
// read input lines and do conversions
while (1) {
if (! doline())
break;
}
#if 0
char str[] = "The xirtaM is acutally the Matrix!";
char j[] = "xirtaM";
char e[] = "Matrix";
char *result = NULL;
printf("Original string: %s\n",str);
printf("The converted sentence: %s",string);
char input[200];
getchar();
fflush(stdin);
fgets(input,200,stdin);
char c;
if (isdigit(c)) {
int n = c - '0'; //'0'-'9' -> 0 - 9
printf("%c is coverted to %d\n",c,n);
}
while((c=getchar()) != EOF) {
if(islower(c))
printf("%c will be converted to %c\n",c,toupper(c));
if(isupper(c))
printf("%c in lowercase is %c\n",c,tolower(c));
getchar();
}
#endif
return 0;
}
Here is the program output for the default test cases:
DEBUG: BEFORE 'The xirtaM is acutally the Matrix!'
DEBUG: AFTCAP 'The xirtam is acutally the matrix!'
DEBUG: AFTFIX 'The Matrix is acutally the matrix!'
DEBUG: BEFORE 'a blACk cAT is in the xirtaM.'
DEBUG: AFTCAP 'A black cat is in the xirtam.'
DEBUG: AFTFIX 'A black cat is in the Matrix.'

Issue with Strings in C

Here is a program with Strings where I am trying
Pig Latin translation is simply taking the first letter of a “word” and appending that letter to the end of the word with “ay” added to the end as well
I have issue with m1=m2+3 ( resetting the Initial Marker ).
Input that I am giving : "Alex, how are you right"
The output I am expecting is : lexay, owhay reay ouyay ightray
But
I am getting this : lex,Aay way ay ayo gayi
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void initialize(char english[], char piglatin[]);
void readinput (char english[]);
int countwords(char english[]);
void convert ( int words, char english[], char piglatin[]);
void writeoutput( char piglatin[]);
int main()
{
char english[80], piglatin[80];
int words;
initialize(english, piglatin);
printf("enter the string\t");
fflush(stdin);
gets(english);
printf ("\nInput buffer contents: %s\n", english);
words = countwords(english);
convert(words,english,piglatin);
writeoutput(piglatin);
printf ("Have a nice day\n");
}
void initialize(char english[], char piglatin[])
{
int count;
for(count =0; count<80;++count)
{
english[count]=piglatin[count]=' ';
}
return;
}
/* Scan the english test and determine the number of words */
int countwords(char english[])
{
int count, words =1;
for ( count =0;count <79;++count)
{
if(english[count]==' ' && english[count+1]!=' ')
++words;
}
printf("%d\n",words);
return (words);
}
/* convert each words in to piglatin*/
void convert ( int words, char english[], char piglatin[])
{
int n, count;
int m1=0;
int m2;
/* convert each word */
for ( n=1;n<=words;++n)
{
/* locate the end of the current word*/
count = m1;
printf ("\ before conversion word contents: %d\n", count);
while ( english[count]!=' ')
{
m2=count++;
}
printf ("\ before conversion word contents: %d\n", m2);
/* transpose the first letter and add 'a', 'y'*/
for (count =m1;count<m2;++count)
{
piglatin[count+(n-1)]=english[count+1];
}
piglatin[m2+(n-1)] = english[m1];
piglatin[m2+1] = 'a';
piglatin[m2+2] = 'y';
m1=m2+3;
printf ("\ Converted word contents: %s\n", piglatin);
}
return;
}
void writeoutput( char piglatin[])
{
int count =0;
for (count =0; count <80; ++count)
{
putchar(piglatin[count]);
}
printf ("\n");
return;
}
I see various problems here:
Alex -> lex,Aay: You should check for punctuation marks when determining the end of the words, thus inserting the Aay part before the comma character
Alex -> lex,Aay: Every character from the start of a word should be converted to lowercase and the resulting first character should be converted to upper case respectively
Now the conversion function: I have changed it a bit to get you started; it should work now ( at least it does with your test string ) without taking 1 and 2 into account though
void convert(int words, char english[], char piglatin[])
{
int estart = 0;
int ppos = 0;
int m2;
for (int n = 0; n < words; n++)
{
//locate the start of the current word, to make
//sure something like this is converted:
//"Alex, how are you"
while (english[estart] == ' ')
{
//make sure we do not exceed the strings boundaries!
if (english[estart] == '\0')
{
return;
}
estart++;
}
//locate the end of the word
int eend = estart;
while (english[eend] != ' ')
{
//never forget to check for the end of the string
if (english[eend] == '\0')
{
break;
}
eend++;
}
/* transpose the first letter and add 'a', 'y'*/
for (int i = estart+1; i < eend; i++, ppos++)
{
piglatin[ppos] = english[i];
}
piglatin[ppos++] = english[estart];
piglatin[ppos++] = 'a';
piglatin[ppos++] = 'y';
//dont forget to add a whitespace or your string might behave
//very stangely!
piglatin[ppos++] = ' ';
estart = eend;
printf("\ Converted word contents: %s\n", piglatin);
}
}
I hope this gets you started in the right direction.
Please also check your array sizes for english and piglatin. The string for piglatin is alway longer than the english one but your array sizes are the same! Also i would advise you add some boundary checks to make sure you do not leave the array boundaries.

A program to remove common alphabets from character array

void main()
{
int i, j, k,flag=1;
char key[10], keyword[10];
gets(key);
i=0;
j=0;
while(key[i]!='\0') {
k=0;
while(keyword[k]!='\0') {
if(key[i]==keyword[k]) {
i++;
flag=0;
break;
}
k++;
}
if(flag==1) {
keyword[j]=key[i];
j++;
i++;
}
flag=1;
}
}
Here I tried to copy unique alphabets from array to another array ..means duplicate alphabet should not copied in another array..it shows right output but along with that it shows some garbage values like smiley or something till the length of original input array(i.e.key[])
You need to add a terminator to the unique character string both at the time it is initialized, and every time a new letter is added:
#include <stdio.h>
int main() {
int i = 0, j = 0;
char redundant[10], unique[10] = { '\0' };
gets(redundant);
while (redundant[i] != '\0') {
int k = 0, flag = 1;
while (unique[k] != '\0') {
if (redundant[i] == unique[k]) {
flag = 0;
break;
}
k++;
}
if (flag) {
unique[j++] = redundant[i];
unique[j] = '\0';
}
i++;
}
printf("%s -> %s\n", redundant, unique);
return(0);
}
OUTPUT
% ./a.out
warning: this program uses gets(), which is unsafe.
aardvark
aardvark -> ardvk
%
Now let's consider a different approach that wastes some space to simplify and speed up the code:
#include <stdio.h>
#include <string.h>
int main() {
unsigned char seen[1 << (sizeof(char) * 8)] = { 0 }; // a flag for every ASCII character
char redundant[32], unique[32];
(void) fgets(redundant, sizeof(redundant), stdin); // gets() is unsafe
redundant[strlen(redundant) - 1] = '\0'; // toss trailing newline due to fgets()
int k = 0; // unique character counter
for (int i = 0; redundant[i] != '\0'; i++) {
if (!seen[(size_t) redundant[i]]) {
unique[k++] = redundant[i];
seen[(size_t) redundant[i]] = 1; // mark this character as seen
}
}
unique[k] = '\0'; // terminate the new unique string properly
printf("%s -> %s\n", redundant, unique);
return 0;
}
Instead of a second, inner loop to search if a letter has been copied already, we use an array of flags (boolean), where the letter is the index, to determine if the letter has been processed.
Another thing you might want to think about is whether to treat upper and lower case differently or fold them into one.

Program that checks if an array is a palindrome

I'm trying to create a program that checks if a given array/string is a palindrome or not and its not working. The program just prints "0" on every given array, even on palindromes.
int main()
{
char string[100]= {0};
char stringReverse[100]= {0};
int temp = 0;
int firstLetter = 0;
int lastLetter = 0;
printf("Please enter a word or a sentence: ");
fgets(string, 100, stdin);
strcpy(stringReverse , string); // This function copies the scanned array to a new array called "stringReverse"
firstLetter = 0;
lastLetter = strlen(string) - 1; //because in array, the last cell is NULL
// This while reverses the array and insert it to a new array called "stringReverse"
while(firstLetter < lastLetter)
{
temp = stringReverse[firstLetter];
stringReverse[firstLetter] = stringReverse[lastLetter];
stringReverse[lastLetter] = temp;
firstLetter++;
lastLetter--;
}
printf("%s %s", stringReverse, string);
if ( strcmp(stringReverse , string) == 0)
{
printf("1");
}
else
{
printf("0");
}
}
Lets say we implement a simple fun to do that
int check_palindrome (const char *s) {
int i,j;
for (i=0,j=strlen(s)-1 ; i<j ; ++i, --j) {
if (s[i] != s[j]) return 0; // Not palindrome
}
return 1; //Palindrome
}
I think this is far more simpler ;)
For the code posted in question:
Be aware of fgets(). It stops in the first '\n' or EOF and keeps the '\n' character.
So if you give radar for ex, the result string will be "radar\n", which doesn't match with "\nradar"
The Problem:
Let's say you enter the string RACECAR as input for your program and press enter, this puts a newline character or a '\n' in your buffer stream and this is also read as part of your string by fgets, and so your program effectively ends up checking if RACECAR\n is a palindrome, which it is not.
The Solution:
After you initialize lastLetter to strlen(string) - 1 check if the last character in your string (or the character at the lastLetter index is the newline character (\n) and if so, decrease lastLetter by one so that your program checks if the rest of your string (RACECAR) is a palindrome.
lastLetter = strlen(string) - 1; //because in array, the last cell is NULL
// Add these 2 lines to your code
// Checks if the last character of the string read by fgets is newline
if (string[lastLetter] == '\n')
lastLetter--;
fgets adds a '\n' at the end.
So if the user entered "aba", string contains "aba\n".
reverseString contains "\naba".
So it doesn't match.
After the fgets, add this code
int l = strlen(string) - 1;
string[l] = 0;
This will strip out the '\n' at the end before copying it to reverseString.
That aside, you can do this whole program inplace without the need of a second buffer or strcpy or strlen calls.
You have several issues in your code:
first you forgot the last closing brace };
then you forgot to remove the trailing \n (or maybe also \r under Windows) in string;
you don't need to revert the string into a new string; a one-pass check is enough:
Here is a working code:
#include <stdio.h>
#include <string.h>
int main()
{
char string[100]= {0};
int temp = 0;
int firstLetter = 0;
int lastLetter = 0;
printf("Please enter a word or a sentence: ");
fgets(string, 100, stdin);
firstLetter = 0;
lastLetter = strlen(string) - 1; //because in array, the last cell is NULL
while ((string[lastLetter]=='\n')||(string[lastLetter]=='\r')) {
lastLetter--;
}
// This while reverses the array and insert it to a new array called "stringReverse"
temp = 1;
while(firstLetter < lastLetter)
{
if (string[firstLetter] != string[lastLetter]) {
temp = 0;
break;
}
firstLetter++;
lastLetter--;
}
if ( temp )
{
printf("1");
}
else
{
printf("0");
}
}
You can do it by this simpleway also.
#include <stdio.h>
#include <string.h>
int main()
{
char string[10], revString[10];
printf("Enter string for reversing it...\n");
scanf("%s", string);
int stringLength = strlen(string);
for(int i = 0; string[i] != '\0'; i++, stringLength--)
{
revString[i] = string[stringLength - 1];
}
if(strcmp(string, revString) == 0)
printf("Given string is pelindrom\n");
else
printf("Given string is not pelindrom\n");
}
#include<stdio.h>
#include<string.h>`enter code here`
void fun(char *a);
int main ()
{
char p[100];
char *s=p;
printf("enter the string");
scanf("%[^\n]",s);
fun(s);
}
void fun(char *a)
{
if(*a && *a!='\n')
{
fun(a+1);
putchar(*a);
}
}
// use this approach better time complexity and easier work hope this helps

Resources