I need to find the repeating characters in 2 strings - c

I'm trying to find the repeating elements in the 2 strings. Here is what I have done.
int main()
{
int i, j;
char S[5];
char J[4];
printf("Enter the 1st string\n");
scanf("%s", &S);
printf("\nEnter the 2nd string\n");
scanf("%s",&J);
printf("\n1st string characters are %s", &S);
printf("\n2nd string characters are %s", &J);
for(i=0; i<5; i++)
{
for (j=0; j<3; j++)
{
if(J[j] == S[i])
{
printf("\n\nThe element is found and is at %c", *(&S[i]));
break;
}
else
{
printf("\nNo matching element found");
break;
}
}
}
return 0;
}
The output im getting is
Enter the 1st string
asdf
Enter the 2nd string
cfv
1st string characters are asdf
2nd string characters are cfv
The element is found and is at
No matching element found
No matching element found
No matching element found
No matching element found
No matching element found
Any idea why this might be happening? I'm a rookie in this. Any help is appreciated

i can make a few suggestions in your loop replace i<5 and j<3 to i<strlen(S) similarly j<strlen(J)
strlen is used to calculate string length.
and do not use break; otherwise it will skip the loop at first match . so try this
#include<stdio.h>
#include <string.h>
int main() {
int i, j;
char S[]="rat";
char J[]="fat";
printf("\n1st string characters are %s", &S);
printf("\n2nd string characters are %s", &J);
for(i=0; S[i] != '\0';; i++)
{
for (j=0; J[j] != '\0';; j++)
{
if(J[j] == S[i])
{
printf("\n\nThe element is found and is at %c", *(&S[i]));
}
else
{
printf("\nNo matching element found");
}
}
}
return 0;
}
click here to see the outputThe output is shown in a image.
sorry i was not having a c compiler in my system so used online one and may be thats why the location is not shown but yes it resolves your problem the matches are being detected.

Related

Unable to store any value in array

I am unable to put the value in the first element of the array. It's always asking to put the value in array second element.
#include<stdio.h>
#include<string.h>
int main(void)
{
int a, i;
char names[50][50];
printf("\nEnter the number of names you want :");
scanf("%d", &a);
for(i = 0; i < a; i++)
{
printf("\n%d name :", i);
gets(names[i]);
}
printf("\nThe required name lists :");
for(int i = 0; i < a; i++)
{
printf("\n%d name :", i+1);
puts(names[i]);
}
return 0;
}
As scanf leaves behind a dangling newline character \n it causes the gets(Use fgets) to not wait for the input from the user. Try flushing the input buffer by using getchar.
Update: Added mechanism to remove the trailing \n registered by the fgets
#include<stdio.h>
#include<string.h>
int main()
{
int a,i;
printf("Enter the number of names you want: ");
scanf("%d",&a);
//Flush the input buffer
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
char names[50][50];
for(i=0;i<a;i++)
{
printf("%d name: ",i);
fgets(names[i],50,stdin); //Use fgets instead of gets
// To remove th \n registed by the fgets
char *p;
if ((p = strchr(names[i], '\n')) != NULL)
*p = '\0';
}
printf("The required name lists: \n");
for(int i=0;i<a;i++)
{
printf("%d name: ",i+1);
puts(names[i]);
}
return 0;
}
Reference:
Remove newline skipped by scanf
Remove newline registered by fgets
Put this after line scanf("%d",&a), as a workaround,
char c;
scanf("%c",&c);
Also use fgets(names[i],50,stdin) instead of gets(names[i])
Note: You get warning when you use gets in your code, as it is always assumes a consistent input from user. More explanation over here
Why is the gets function so dangerous that it should not be used?

replace one word with another in a string

can anyone say me what is the mistake here. I used two dimensional array here.
#include<stdio.h>
#include<string.h>
int main()
{
char a[100], b[30][30], c[20], d[20];
int i, j=0, k, count=0;
int e[30];
printf("enter a string: ");
gets(a);
printf("enter the word which has to be replaced: ");
gets(c);
printf("enter the word with which it has to be replaced: ");
gets(d);
for(i=0,k=0, e[i]=0; i<strlen(a); i++, k++)
{
if(a[i]==' ')
{
k=0;
j++;
count++;
}
else
{
b[j][k]=a[i];
e[i]++;
}
}
for(i=0; i<j; i++)
{
if(word(b[i], c)==0)
{
for(k=0; k<strlen(d); k++)
{
b[i][k]=d[k];
}
}
}
for(i=0; i<count; i++)
{
for(j=0; j<e[i]; j++)
{
printf("%c", b[i][j]);
}
printf(" ");
}
}
int word(char *a, char *c)
{
int i;
if(strlen(a)==strlen(c))
{
for(i=0; i<strlen(a); i++)
{
if(a[i]!=c[i])
{
return 1;
}
}
}
else
return 2;
return 0;
}
I want the output to be like the below.
For example:
enter a string: vicky is a good boy
enter the word which has to be replaced: good
enter the word with which it has to be replaced: bad
vicky is a bad boy
I mean I want to replace only that particular word, as many times as it appears in the string such as here, the word good. Can anyone help me identify the mistake or help me find another way.
You should not use gets, it's dangerous: Why is the gets function so dangerous that it should not be used?.
You should use fgets to read from stdin instead.
Int the word function, you compare length of two string using strlen funciton:
if(strlen(a)==strlen(c))
But in the main function, you call it as:
if(word(b[i], c)==0)
b[i] is array of character, but you do not add null character \0 at the end of each word. So strlen will not work as you think.
In the code that you replace string c by d. You not update value of e array.
I think, e[i] should be:
e[i] = strlen(d);
I seem that you do not use some standard function for string, for example, very useful for your program.
strcmp to compare string and string.
strstr to find the word in the string.
If you search in google, you can have a ton of code for your case.
for example: program to Replace a word in a text by another given word
another: Replacing Words inside string in C

Char array pointer in C

I want to run this code but i can not. i have yet started to learn pointer in C. I am trying to get the addresses of letters. Problem is printf("in adress: %p\n",p[i]);` Thanks
#include <stdio.h>
int main(void){
char letter;
int c=0;
int i;
char pattern[7];
char *p;
printf("Enter a letter: ");
scanf("%c",&letter);
printf("Enter a pattern: ");
scanf("%s",pattern);
p=pattern;
for(i=0;i<7;i++)
{
if(letter==pattern[i])
{
c++;
printf("Letter < %c > is found in pattern %s\n",letter,pattern);
printf("in adress: %p\n",p[i]);
printf("index:%d\n",i);
}
}
if(c==0)
printf("The pattern does not include any letter");
return 0;
}
This line of code has some potential problem that can easily happen
scanf("%s",&pattern);
you can make it a little bit safer like this
scanf("%6s",&pattern);
it's a 6 because you need one extra byte '\0' at the end of the string, which takes us to the next problem
for(i=0;i<7;i++)
here you are assuming that all bytes are non-nul which would be ok except that you are reading a string with scanf() and unless you create the array one byte bigger than the number of characters you want to store in it, scanf() will overflow the array i.e. write a byte beyond it's bounds.
Adding the "%6s" length specifier to the format string solves this, but you can only store 6 non-nul bytes in the array, and for the other problem
for (i = 0 ; pattern[i] != '\0' ; i++)
would be better, because you don't need to know the length of the string in advance and you don't risk reading past the end of the array.
Try this:
#include <stdio.h>
int main(void)
{
char letter;
char c;
int i;
char pattern[7];
printf("Enter a letter: ");
if (scanf(" %c",&letter) != 1)
{
printf("error: invalid input.\n");
return -1;
}
printf("Enter a pattern: ");
if (fgets(pattern, sizeof(pattern), stdin) == NULL)
{
printf("error: end of file.\n");
return -1;
}
for (i = 0 ; pattern[i] != 0 ; ++i)
{
if (letter == pattern[i])
{
c++;
printf("Letter < %c > is found in pattern %s\n", letter, pattern);
printf("in adress: %p\n", pattern + i);
printf("index :%d\n", i);
}
}
if (c == 0)
printf("The pattern does not include any letter");
return 0;
}
You also was printg the address wrong, because in pointer[i] the subscript operator dereferences the pointer, it's equivalent to *(poitner + i).

How can I replace getchar();?

#include <stdio.h>
int main (void)
{
int n;
printf("Give the number of words you want to input.");
scanf("%d",&n);
int letters[n],i,j,count,key,k;
char str[100];
//Scans each word, counts it's letters and stores it in the next available
//position in "letters" array.
for (i=0;i<n;i++)
{
j=0;
printf("Give the next word.");
do{
str[j] = getchar();
j++;
}while (str[j-1]!='\n');
str[j-1] = '\0';
letters[i] = j;
}
//Compacts the data by figuring out which cells have the same number of letters
for (i=0;i<n;i++)
{
key = letters[i];
count = 0;
for (j=i+1;j<=n;j++)
{
if (key==letters[j])
{
count += 1;
letters[j] = 0;
}
}
letters[i] = count;
}
//creates a histogram
i=0;
do{
printf("%d|",i);
for (j=1;j<=letters[i];j++)
{
printf("*");
}
printf("\n");
i++;
}while ((i<=n));
return 0;
}
I understand that getchar(); reads, the first enter (\n) , user hits, to give the amount of words he wants to input, and thus expects one less word.
Also, I get an infite loop for some reason at the end. Any help and ideas would be appreciated. Thanks in advance.
Change the first block of your code to look like this:
(test the output of getchar, and continues only if not EOF)
for (i=0;i<n;i++)
{
j=0;
printf("Give the next word.");
do{
a = getchar();
if(a >= 0)
{
str[j] = a;
j++;
}
else break;
}while (str[j-1]!='\n');
str[j-1] = '\0';
letters[i] = j;
}
But regarding your question: How can I replace getchar();? Have you considered using scanf()?
EDIT
Here is a simple example of using scanf() and printf() to prompt for input and then display input. It will allow user to input entire words or sentences (up to 80 characters) until 'q' is entered. Not exactly what you are doing, but you should be able to adapt it to your code... (run this)
int main(void)
{
char buf[80]={""};
while( strcmp(buf, "q") != 0) //enter a 'q' to quit
{
buf[0]=0;
printf("enter string:\n");
scanf("%s", buf);
printf("%s\n", buf);
}
}
Wouldn't it be easier to update the letter count in the first loop?
memset(letters, 0, n);
for (i=0;i<n;i++)
{
char* s = str;
int j=0;
printf("Give the next word.");
do{
*s = getchar();
++j;
}while (*(s++)!='\n');
s[-1] = '\0';
letters[j-1]++;
}
As a result the second loop will be unnecessary.
The following two lines have the wrong end condition; should be <n, not <=n. Currently they retrieve an uninitialized array element. Since you declared str as a local variable, that element is typically populated with garbage, i.e. a very big random number. That might explain why it takes extreme long (but possibly not forever) for the last loop to finish.
for (j=i+1;j<=n;j++)
}while ((i<=n));
Also, I assume line n of the histogram should contain the number of words that have n letters? That's not what you're doing right now.
letters[i] = count;
That line should have been:
letters[key] = count;
But to make that work, you should not overwrite the same array letters; you must declare a new array for your histogram, otherwise the second loop will destroy its own input.
By the way, str seems totally redundant. Is it there for debugging purposes?

trying to run two parts of program second part can't input string

I am trying to get both parts of this program to work as you can see I have split it with first part (question 1) and second part (question 2). The problem is first part runs fine just when the second part starts I can not input any string and it just seems to skip through the code without letting me input the string.
If I delete the first part (question 1) of the program then everything works fine and I can input the string. What interrance is causing this issue.
int main()
{
first();
second();
}
//Question 1
int first()
{
/* dataarray.c */
float data[20] = {
50.972438, 93.765053, 9.252207, 1.851414, 16.717533,
71.583113, 97.377304, 20.352015, 56.309875, 0.072826,
23.986237, 36.685959, 80.911919, 86.621851, 53.453706,
96.443735, 29.845786, 18.119300, 31.079443, 52.197715 };
/* The number of elements in the data array */
int data_size = 20;
int pos;
int j;
int i;
int k;
printf("Question 1\n");
for(i=0;i<data_size;i++)
{
printf("\nArray %i is %f ",i,data[i]); //Initial arrays print statement
}
printf("\n\nArray number to delete:"); //User Choose one to delete
scanf("%i",&pos);
k =0;
for(j = 0; j< pos;j++)
{
printf("\n Array %i is now %f ",k,data[j]);
k++;
}
k=pos;
for(j=pos+1;j<data_size;j++)
{
printf("\n Array %i is now to %f ",k,data[j]); //Shows array changed to
k++;
}
data_size = data_size - 1; //Decreases data size
}
//Question 2
int second()
{
printf("\n\nQuestion 2\n");
int a,b,check=0;
char str[20];
printf("\nEnter a String:\n"); //User inputs word to check if its palindrome
gets(str);
for(b=0;str[b]!=0;b++); //Starts at 0 increment till the last length
b=b-1;
a=0;
while(a<=b)
{
if(str[a]==str[b]) //String a is forwards b is backwards
{
a=a+1;
b=b-1;
check=1; //If check = 1 then a palindrome
}
else
{
check=0; //If check = 0 then it not a plaindrome
break; //Loop break
}
}
if(check==1)
printf("It is a Palindrome:"); //Statement printed if check = 1
else
printf("It is not a Palindrome\n"); // Else if 0 this statement is printed
}
When you call scanf in part one, I presume you enter a number followed by a newline. scanf consumes the number, but the newline is left in the buffer. The gets() in part 2 then sees the newline and returns a blank line. An easy solution is to do
scanf( "%i\n", &pos );
BTW, never use gets. Use fgets instead.

Resources