Write C a program to find whether the 2 given strings are anagrams or not.
Input consists of 2 string. Assume that all characters in the string are lowercase letters or spaces and the maximum length of the string is 100.
Sample Input and Output 1:
Enter the first string
anitha
Enter the second string
amphisoft
anitha and amphisoft are not anagrams
Sample Input and Output 2:
Enter the first string
the eyes
Enter the second string
they see
the eyes and they see are anagrams
Sample Input and Output 3:
Enter the first string
dormitory
Enter the second string
dirty room
dormitory and dirty room are anagrams
#include <stdio.h>
int check_anagram(char [], char []);
int main()
{
char a[100], b[100];
int flag;
printf("Enter first string\n");
gets(a);
printf("Enter second string\n");
gets(b);
flag = check_anagram(a, b);
if (flag == 1)
printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
else
printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);
return 0;
}
int check_anagram(char a[], char b[])
{
int first[26] = {0}, second[26] = {0}, c = 0;
while (a[c] != '\0')
{
first[a[c]-'a']++;
c++;
}
c = 0;
while (b[c] != '\0')
{
second[b[c]-'a']++;
c++;
}
for (c = 0; c < 26; c++)
{
if (first[c] != second[c])
return 0;
}
return 1;
}
I write the code but it was working only for first one input/output but second and third one input it was not working.
The code you provided works.
Since you are writing it works only for the first input, I'm guessing the problem was in the loop area which you removed to post the question.
One possible reason for it not to work after the first time, is not clearing a and b before getting new input.
Hope I helped,
Related
This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed last year.
I wanted to do a palindrome but when I do the code below:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char string[100];
int comparison;
char again;
printf("This program will determine whether a word is a Palindrome or not.\n");
do
{
start:
int c;
printf("Enter the word: \n");
scanf("%s", string);
int length = strlen(string);
char palindrome[length];
for(int i = 0; i<length; i++)
{
palindrome[i] = string[length-1-i];
printf("%c\n", palindrome[i]);
int validation = isalpha(palindrome[i]);
if(validation==0)
{
printf("Invalid Input! The input must be letters.\n");
goto jump;
}
}
printf("%s\n", palindrome);
comparison = strcmp(string,palindrome);
if(comparison == 0 )
{
printf("The word %s is a palindrome.\n", palindrome);
}
else
{
printf("The word %s is not a palindrome.\n", palindrome);
}
printf("Do you want to restart the code? Input Y to restart, otherwise any key to terminate \n" );
scanf("%s", &again);
while ( (c = getchar()) != '\n' && c != EOF ) { }
}
while((again == 'Y') || (again == 'y'));//this will then loop back the code if again is Y, otherwise continues to the next chunk
printf("Code terminated");
return 0;
jump://If an invalid input will be placed, the code will jump here
printf("Do you want to restart the program? Input Y to restart, otherwise any key to terminate \n" );
char again2;
scanf(" %c", &again2);
if((again2 == 'Y') || (again2 == 'y'))
{
goto start;//jumpts to the start on the top
}
printf("Code terminated");
return 0;
}
When I input racecar, the code will execute correctly.
But when I input the word civic I get this:
civic
c
i
v
i
c
civic⌂
The word civic⌂ is not a palindrome.
Why is there an additional character ⌂?Thank you
Add null terminator ('\0') at the end of the string palindrome.
For example:
palindrome[length] = '\0';
Add the above line after copying all the character from string array to palindrome array.
If your string is not terminated with \0, it might still print the expected output because following your string is a non-printable character in your memory. This is a bug though, since it might blow up when you might not expect it. Always terminate a string with '\0'.
Note: As you're adding length number of character in the palindrome array, declare the size of palindrome array length +1 ( i.e. char palindrome[length + 1];)
I am just running a code to find the length of a given string input by the user in C programming language. I used a loop condition to determine the length but statements inside loop executes when the condition is false also. The code I have tried in c is:
#include <stdio.h>
#define ArrayLength 50
int StringLengthCount();
int main() {
printf("Hello, World!\n");
/*Question: Find inserted string's length, without build in function*/
int c=StringLengthCount();
printf("Your inserted string's length is:%d",c);
return 0;
}
int StringLengthCount(){
printf("\n");
printf("Please enter a sentence to find its length of character:");
char array1[ArrayLength];
fgets(array1,ArrayLength,stdin);
printf("Your inserted string is:%s\n",array1);
int i=0;
int count=0;
while(array1[i]!='\0'){
count++;
printf("%d character is %c",count,array1[i]);
printf("\n");
i++;
}
printf("\n");
printf("Your inserted string's total character i.e string length is:%d",count);
}
I am expecting the result 2 for a sample string input "we", but it gives result 3.
The output result in CLion compiler is given below
enter image description here
Can you kindly tell me why it happens?
If by "statements inside loop executes when the condition is false also" you mean that you see an extra character every time you execute remember that also the line feed (LF alias \n) character that you use to enter your string is part of the acquired string.
So even the empty string has one character that is \n or 0x10.
Your check should be something like this:
while (array1[len] != '\0' && array1[len] != '\n' )
And you function, as suggested in the comments, should have a return and could use just one variable like this:
int StringLengthCount() {
printf("\n");
printf("Please enter a sentence to find its length of character:");
char array1[ArrayLength];
fgets(array1, ArrayLength, stdin);
printf("Your inserted string is:%s\n", array1);
int len = 0;
while (array1[len] != '\0' && array1[len] != '\n' ) {
printf("%d character is %c", len + 1, array1[len]);
printf("\n");
len++;
}
printf("\n");
printf("Your inserted string's total character i.e string length is:%d\n\n",
len);
return len;
}
The function fgets will also read the newline character, so you need to change the condition in the while-loop from str[i] != '\0' to str[i] != '\n'. I have also implemented the suggested changes by Devolus.
#include <stdio.h>
#include <stdlib.h>
#define LEN 50
void string_length();
int main(void)
{
string_length();
return EXIT_SUCCESS;
}
void string_length(void)
{
printf("Enter a string: ");
char str[LEN];
fgets(str, LEN - 1, stdin);
printf("Your entered string is: %s\n", str);
int i = 0;
while (str[i] != '\n') {
printf("The %d. character is '%c'.\n", i + 1, str[i]);
++i;
}
printf("\nThe string's length is %d.\n", i);
}
In this exercise I put two words then I do a function to check if they are anagram, but there is an error in the output knowing that the outpout is true of which there is the same length of the two words
Example of words Anagram:
bob - obb
users - resus
can you help me...
bool Anagram(int l, int k, char T1[l],char T2[k])
{
int i = 0;
while (i < l)
{
for (int j = 0; j < k; j++)
{
if (T1[i] != T2[j])
{
return 0;
}
}
i++;
}
return 1;
}
int main()
{
char T1[100], T2[100];
printf("Give the first word :");
gets(T1);
int k = strlen(T1);//k is the length of the first word
printf("Give the second word :");
gets(T2);
int l = strlen(T2);//l is the length of the second word
if (l != k)
{
printf("\nThe two words are not Anagrams !\n");
return 0;
}
else
{
if (Anagram(l, k, T2, T1) == true)
{
printf("\nThe two words are Anagrams !\n");
}
else
{
printf("\nThe two words are not Anagrams !\n");
}
}
}
qsort is your friend! Why reinvent the wheel? The stdlib provides all means for this task!
Whitespace can easily be stripped after sorting using strcspn, as each of the whitespace chars ascii code is < alnum characters ascii code.
If you don't want to rely on those ascii properties, the compare_chars function can easily adapted so that all whitespace are sorted either to the front or to the end (In the example it sorts the ws to the end).
I wonder if somebody comes up with a unicode version of isAnagram.
Please note that i applied the sorting on a copy of the original strings so that the isAnagram function does not mess up the input.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
int compare_chars(const void *c1, const void *c2)
{
// Sign corresponds to backward sorting so that
// whitespace appears at the end
return *(char *)c2 - *(char *)c1;
}
void sort_remove_whitespace(const char *src, char dest[strlen(src) + 1])
{
strcpy(dest, src);
qsort(dest, strlen(dest), sizeof(char), compare_chars);
dest[strcspn(dest, " \b\t\v\r\n")] = '\0';
}
bool isAnagram(char* T1, char *T2)
{
char T1_copy[strlen(T1) + 1];
char T2_copy[strlen(T2) + 1];
sort_remove_whitespace(T1, T1_copy);
sort_remove_whitespace(T2, T2_copy);
printf("T1 sorted: '%s', T2 sorted: '%s'\n", T1_copy, T2_copy);
return 0 == strcmp(T1_copy, T2_copy);
}
void prompt(const char *msg, char *buf, size_t N)
{
char *fgets_return;
puts(msg);
fgets_return = fgets(buf, N, stdin);
if (NULL == fgets_return)
{
printf("Input error!");
exit(-1); // fail fast fail early
}
printf("OK. Got %s\n", buf);
}
int main()
{
char T1[100], T2[100];
prompt("Give the first word :", T1, sizeof(T1));
prompt("Give the second word :", T2, sizeof(T2));
if ( isAnagram(T1, T2) )
{
printf("The two words are Anagrams !\n");
}
else
{
printf("The two words are not Anagrams !\n");
}
return 0;
}
Example output:
Give the first word :
dead beef
OK. Got dead beef
Give the second word :
fat thief
OK. Got fat thief
T1 sorted: 'feeeddba', T2 sorted: 'ttihffea'
The two words are not Anagrams !
Give the first word :
anagram
OK. Got anagram
Give the second word :
nag a ram
OK. Got nag a ram
T1 sorted: 'rnmgaaa', T2 sorted: 'rnmgaaa'
The two words are Anagrams !
The biggest problem is with your concept of Anagram. The classic example is:
"anagram"
"nag a ram"
Each uses the same letters exactly once with whitespace ignored.
There are several ways to approach determining in two strings are an anagram. You can either use a single array (generally of 128 integer values initialized all zero to cover all characters in the ASCII character set, or 256 to also cover the Extended-ASCII characters.
With the single array, you simply loop over each string. With the first string for each non-whitespace character you increment the index corresponding to the ASCII value of the character, and for the second string you decrement the value at the index corresponding to the ASCII value of the character. At the end, if each character in each string is used exactly the same number of times -- all array values will be zero which will confirm an anagram.
Using two arrays of the same size (either 128 or 256), you simply loop over the characters in each string and for each non-whitespace character you increment the index corresponding to that characters ASCII value in similar fashion, but when done, you compare whether the two arrays are equal to each other with a loop or memcmp().
A short implementation would be:
#include <stdio.h>
#include <ctype.h>
#define NCHARS 256 /* constant to count array size, covers ASCII + extended ASCII */
int isanagram (const char *s1, const char *s2)
{
int count[NCHARS] = {0}; /* counting array, covers all extended ASCII */
for (; *s1; s1++) /* loop over chars in string 1 */
if (!isspace(*s1)) /* if not whitespace */
count[(int)*s1]++; /* add 1 to index corresponding to char */
for (; *s2; s2++) /* loop over chars in string 2 */
if (!isspace(*s2)) /* if not whitespace */
count[(int)*s2]--; /* subtract 1 from index corresponding to char */
for (int i = 0; i < NCHARS; i++) /* loop over counting array */
if (count[i]) /* if any index non-zero, not anagram */
return 0;
return 1; /* all chars used same number of times -> anagram */
}
(NULL parameter checks omitted above, add for completeness)
To test you could use a simple main() that reads two strings and then checks the return from the function above. A return of 1 (true) means the words are anagrams, otherwise they are not anagrams. Simple press Enter alone on a line to quit.
int main (void) {
char str1[NCHARS * 4], str2[NCHARS * 4]; /* arrays for string 1 & string 2 */
for (;;) { /* loop continually */
fputs ("\nenter string 1: ", stdout);
if (!fgets (str1, sizeof str1, stdin) || *str1 == '\n') /* EOF or ENTER alone */
break;
fputs ("enter string 2: ", stdout);
if (!fgets (str2, sizeof str2, stdin) || *str2 == '\n') /* EOF or ENTER alone */
break;
printf ("\nwords %s an anagram\n", isanagram (str1, str2) ? "are" : "are not");
}
}
Example Use/Output
$ ./bin/anagram_count_array
enter string 1: anagram
enter string 2: nag a ram
words are an anagram
enter string 1: anagram
enter string 2: naag a ram
words are not an anagram
enter string 1: cat
enter string 2: tac
words are an anagram
enter string 1: cat
enter string 2: a t c
words are an anagram
enter string 1:
Look things over and let me know if you have questions.
As I understand your anagram is just the word with ordered other wany same letters.
#define NCHARS (127-31)
int *freq(const char *str)
{
int *freqTable = calloc(NCHARS, sizeof(freqTable)) ;
if(freqTable)
{
while(*str)
{
if( *str < ' ')
{
free(freqTable);
freqTable = NULL;
break;
}
freqTable[*str++ -' ']++;
}
}
return freqTable;
}
bool isAnagram(const char *str1, const char *str2)
{
int *freq1 = freq(str1), *freq2 = freq(str2);
bool result = false;
if(freq1 && freq2)
{
result = !memcmp(freq1, freq2, sizeof(*freq1) * NCHARS);
}
free(freq1); free(freq2);
return result;
}
int main(void)
{
printf("%d", isAnagram("bob", "obb"));
}
In this program I have taken a dimensional character array of size[3][4],
as long as I enter a 3 characters for each row it will work well.
For example: if I enter abc abd abd I get the same output but if i enter more letters in the first or second or 3rd row I get an error.
How should I check for null character in 2 dimensional?
# include <stdio.h>
#include <conio.h>
# include <ctype.h>
void main()
{
int i=0;
char name[3][4];
printf("\n enter the names \n");
for(i=0;i<3;i++)
{
scanf( "%s",name[i]);
}
printf( "you entered these names\n");
for(i=0;i<3;i++)
{
printf( "%s\n",name[i]);
}
getch();
}
As pointed out by #SouravGhosh, you can limit your scanf with "%3s", but the problem is still there if you don't flush stdin on each iteration.
You can do this:
printf("\n enter the names \n");
for(i = 0; i < 3; i++) {
int c;
scanf("%3s", name[i]);
while ((c = fgetc(stdin)) != '\n' && c != EOF); /* Flush stdin */
}
How should I chk for null character in 2 dimensional ... [something has eaten the rest part, I guess]
You don't need to, at least not in current context.
The problem is in your approach of allocating memory and putting input into it. Your code has
char name[3][4];
if you enter more that three chars, you'll be overwriting the boundary of allocated memory [considering the space of \0]. You've to limit your scanf() using
scanf("%3s",name[i]);
Note:
change void main() to int main(). add a return 0 at the end.
always check the return value of scanf() to ensure proper input.
EDIT:
As for the logical part, you need to eat up the remainings of the input words to start scanning from the beginning of the next word.
Check the below code [Under Linux, so removed conio.h and getch()]
# include <stdio.h>
# include <ctype.h>
int main()
{
int i=0; char name[3][4];
int c = 0;
printf("\n enter the names \n");
for(i=0;i < 3;i++)
{
scanf( "%3s",name[i]);
while(1) // loop to eat up the rest of unwanted input
{ // upto a ' ' or `\n` or `EOF`, whichever is earlier
c = getchar();
if (c == ' ' || c == '\n' || c == EOF) break;
}
}
printf( "you entered these names\n");
for(i=0;i<3;i++)
{
printf( "%s\n",name[i]);
}
return 0;
}
(Cringing after reading the answers to date.)
First, state the problem clearly. You want to read a line from stdin, and extract three short whitespace separated strings. The stored strings are NUL terminated and at most three characters (excluding the NUL).
#include <stdio.h>
void main(int, char**) {
char name[3][4];
printf("\n enter the names \n");
{
// Read tbe line of input text.
char line[80];
if (0 == fgets(line, sizeof(line), stdin)) {
printf("Nothing read!\n");
return 1;
}
int n_line = strlen(line);
if ('\n' != line[n_line - 1]) {
printf("Input too long!\n");
return 2;
}
// Parse out the three values.
int v = sscanf(line, "%3s %3s %3s", name[0], name[1], name[2]);
if (3 != v) {
printf("Too few values!\n");
return 3;
}
}
// We now have the three values, with errors checked.
printf("you entered these names\n%s\n%s\n%s\n",
name[0], name[1], name[2]
);
return 0;
}
you might consider something on the order of scanf( "%3s%*s",name[i]);
which should, if I recall correctly, take the first three characters (up to a whitespace) into name, and then ignore anything else up to the next white space. This will cover your long entries and it does not care what the white space is.
This is not a perfect answer as it will probably eat the middle entry of A B C if single or double character entries are mode. strtok, will separate a line into useful bits and you can then take substrings of the bits into your name[] fields.
Perhaps figuring out the entire requirement before writing code would be the first step in the process.
I am trying to write a program that adds, subtracts, multiplies, and divides a string of characters. Where I'm at now with the program is figuring out how to split the input string into two strings, and then perform the appropriate +-/*.
The input should look like this abc+aaa
and the output for that should be abc + aaa = bcd
How do I convert character strings into integer strings?
#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
printf("This is a pseudo arithmetic program");
char input[10];
input[10] = '\0';
char first [9];
first[9] = '\0';
char last [9];
last[9] = '\0';
int i = 0;
int b;
int e;
while (input[0] != '0') {
if (input[0] == 0){
return -1;
}
printf("\nEnter a math problem in SOS format using only lowercase letters up to 9 characters");
printf("\nEx: abc+abc... type '0' to quit \n");
scanf("%s", input);
int x = 0;
x = strlen(input);
if (strchr(input, '+')){
for (i = 0; i <= x; i++) {
if (i == '+')
strncpy(first, &input[0], i-1);
i = 0;
}
for (i = x; i >= input[0]; i--) {
if (i == '+')
strncpy(last, &input[i], x);
i = 0;
}
printf("%s", first);
printf(" + ");
printf("%s", last);
printf(" = %d", first + last);
}
There seems to be multiple problems with your code:
There is a array out of bounds happening for almost all the arrays:
char input[10];
input[10] = '\0';
In this if you want to initialize the last character with '\0' then it should be
input [9] = '\0'
Arrays indexes always start from 0.
It is not clear what is the use of below lines:
while (input[0] != '0') { if (input[0] == 0){ return -1; }
When taking input for a string, why are prompting users to enter a 0 to end it?
strrchr returns the pointer from where the searched character begins. So, you can that itself to determine where the '+' symbol is and two split the strings instead of your while loop. See strrchr man page
Also, your idea of adding characters is not clear. From your example, it appears you are considering a = 1, b = 2 etc. In such a case, if your code is case insensitive, then you can convert all your input to upper case and then do (input[0] - 'A')+1 to convert your letters like a, b, c to 1, 2, 3 etc.
Hope these pointers help. Suggest you check your problem statement again and refactor your code accordingly.