Finding the common characters present in all strings [closed] - c

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 8 years ago.
Improve this question
Compare each string and find the number of common lowercase letter in all the strings.
Each string is represented by a lowercase letter from 'a' to 'z'.
Example Input:
4
abcf
aghb
acbl
bamn
Example Output:
2 // a and b
Code:
#include<stdio.h>
#include<string.h>
int main() {
int n;
scanf("%d\n",&n);
char str[n][100];
char var[0][100];
for(int i=0; i<n; i++) { // strings
scanf("%99s/n",str[i]);
}
for(int i=0;i<100;i++) { // comparison of first 2 strings
for(int k=0;k<100;k++)
if(str[0][i]==str[1][k])
for(int j=0;j<strlen(str[0]);j++) {
var[0][j]=str[0][j]; // storing the common letters in a var array
}
}
for(int l=0; l<strlen(str[1]); l++) { // comparing letters in var array with the letters of all other strings
int x;
if(var[0][l]==str[l+2][l]);
x=strlen(var[0]); // counting the common letters
printf("%d\n",x);
}
return 0;
}

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
int n;
scanf("%d",&n);
char str[n][100];
char var[n][26];
memset(&var[0][0], 0, sizeof(var));
for(int i=0; i<n; i++) {
scanf("%99s", str[i]);
char ch;
for(int j=0; ch=str[i][j]; ++j){
if(islower(ch)){
var[i][ch-'a']=1;//depend on the sequence of character codes
}
}
}
int x = 0;
for(int i=0; i<26; ++i){
int num = 0;
for(int j=0;j<n;++j)
if(var[j][i])
++num;
if(num==n)//all string has character of ('a'+i)
++x;
}
printf("%d\n",x);
return 0;
}

Not sure why you would want to special-case the first two strings here? How about an approach like this (in pseudocode):
- create a set of characters, name it letters_in_all_strings
- add every lowercase letter to letters_in_all_strings
- for each input string
- create a set of characters, name it letters_in_this_string
- add every character in the input string to letters_in_this_string
- remove all letters from letters_in_all_strings that are not present in letters_in_this_string
- print out the size of letters_in_all_strings
You could use an array of 0s and 1s, indexed by char, to implement a set of chars in C. Or you could use glib (https://stackoverflow.com/a/2502721/2186890). Or maybe consider using a more modern programming language?

Related

How to find duplicate letter in array in C

I am making a program which requires the user to input an argument (argv[1]) where the argument is every letter of the alphabet rearranged however the user likes it. Examples of valid input is "YTNSHKVEFXRBAUQZCLWDMIPGJO" and "JTREKYAVOGDXPSNCUIZLFBMWHQ". Examples of invalid input would then be "VCHPRZGJVTLSKFBDQWAXEUYMOI" and "ABCDEFGHIJKLMNOPQRSTUYYYYY" since there are duplicates of 'V' and 'Y' in the respective examples.
What I know so far is, that you can loop through the whole argument like the following
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
//Place something in here...
}
However, I do not quite know if this would be the right way to go when looking for duplicates? Furthermore, I want the answer to be as simple as possible, right know time and cpu usage is not a priority, so "the best" algorithm is not necessarily the one I am looking for.
Try it.
#include <stdio.h>
#include <stddef.h>
int main()
{
char * input = "ABCC";
/*
*For any character, its value must be locate in 0 ~ 255, so we just
*need to check counter of corresponding index whether greater than zero.
*/
size_t ascii[256] = {0, };
char * cursor = input;
char c = '\0';
while((c=*cursor++))
{
if(ascii[c] == 0)
++ascii[c];
else
{
printf("Find %c has existed.\n", c);
break;
}
}
return 0;
}
assuming that all your letters are capital letters you can use a hash table to make this algorithm work in O(n) time complexity.
#include<stdio.h>
#include<string.h>
int main(int argc, char** argv){
int arr[50]={};
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
arr[argv[1][j]-'A']++;
}
printf("duplicate letters: ");
for(int i=0;i<'Z'-'A'+1;i++){
if(arr[i]>=2)printf("%c ",i+'A');
}
}
here we make an array arr initialized to zeros. this array will keep count of the occurrences of every letter.
and then we look for letters that appeared 2 or more times those are the duplicated letters.
Also using that same array you can check if all the letters occured at least once to check if it is a permutation
I don't know if this is the type of code that you are looking for, but here's what I did. It looks for the duplicates in the given set of strings.
#include <stdio.h>
#include <stdlib.h>
#define max 50
int main() {
char stringArg[max];
int dupliCount = 0;
printf("Enter A string: ");
scanf("%s",stringArg);
system("cls");
int length = strlen(stringArg);
for(int i=0; i<length; i++){
for(int j=i+1; j<length; j++){
if(stringArg[i] == stringArg[j]){
dupliCount +=1;
}
}
}
if(dupliCount > 0)
printf("Invalid Input");
printf("Valid Input");
}
This code snippet is used to count the duplicate letters in the array.
If you want to remove the letters, Also this code snippet is helpful .Set null when the same characters are in the same letter.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count=0;
int array[]={'e','d','w','f','b','e'};
for(int i=0;i<array.Lenth;i++)
{
for(int j=1;j<array.Length;j++)
{
if(array[i]==array[j])
{
count++;
}
}
}
printf("The dublicate letter count is : %d",count);
}

warning array comparison between pointer and integer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
So i have this problem where i have to input a string of unknown size with only lowercase letters then output the number of distinct letters.this is the main program
#include <stdio.h>
#include <ctype.h>
int test(char *T);
int main(){
char T[100];int i=-1,j=0,nd=0;
do{
gets(T);
}while((test(T))==1);
do {
i++;
j=i;
do{j++;
}while ((T[i]!=T[j])||((T[j])!=""));
if (T[j]=="")
nd++;
}while (T[i+1]!="");
and this is my function test
int test(char *T){
int i=-1,s;
do {
i++;
}while (((islower(T[i])==1))||(T[i]==""));
if ((T[i]=="")&&(i!=0))
s=0;
else s=1;
return s;
}
the problem is that i get a lot of warnings "comparison between integer and pointer" everytime i compare a char of the array T and i don't knowhow to fix that.your help would be much appreciated.
Update:So i tried fixing the program following your advices and this is the new main program
#include <stdio.h>
#include <ctype.h>
int test(char *T);
int main(){
char T[100];int i=-1,j=0,nd=0;
do{
gets(T);
}while((test(T))==1);
do {
i++;
j=i;
do{j++;
}while ((T[i]!=T[j])||((T[j])!='\0'));
if (T[j]=='\0')
nd++;
}while (T[i+1]!='\0');
printf("%d",nd);}
and this is function test
int test(char *T){
int i=-1,s;
do {
i++;
}while (((islower(T[i])==1))||(T[i]=='\0'));
if ((T[i]=='\0')&&(i!=0))
s=0;
else s=1;
return s;
}
I don't get anymore warnings and the program gets compiled with no problems but after i input the string in the execution nothing happens.
You function test should return 1 if the string contains only lowercase letters, and 0 otherwise. Unfortunately, it is not doing that.
You should first test if the character is a letter and then if it's a lowercase letter. Or more efficiently, you test if the character is in the range 'a' to 'z'.
Another problem of your code is the use of do while loops which makes the code difficult to understand and executes the loop once.
Here is a better implementation of the test function:
int test(char *T){
// reject empty strings
if(T[0] == '\0')
return 0;
// reject strings containing non lowercase letter
for(int i = 0; T[i] != '\0'; i++)
if((T[i] < 'a') || (T[i] > 'z'))
return 0;
// string is not empty and contains only lowercase letters
return 1;
Counting the different letters can be made more readable by using a for loop instead of a go while loop.
int nd = 0;
for(int i = 0; T[i] != '\0'; i++) {
for(int j = 0; j < i; j++) {
if(T[j] == T[i])
break; // quit inner loop
nd++;
}
}
This code examine each letter and see if it has been seen before. It is thus different from yours.
A problem in your code is the test (T[i]!=T[j])||((T[j])!='\0'). It should be && instead of ||, and testing if the end of string is reached should be performed first. The test should be (T[j]!='\0')&&(T[i]!=T[j]).
So my code is finally working here's the final main program
#include <stdio.h>
#include <ctype.h>
int test(char *T);
int main(){
char T[100];int i,j,nd=0;
do{
gets(T);
}while((test(T))==0);
for(i = 0; T[i] != '\0'; i++) {
j=i;
do{
j++;
}while ((T[j]!='\0')&&(T[j]!=T[i]));
if (T[j]=='\0')
nd++;
}
(#chmike i used the code you posted with a little adjustment on the loop)
and for the function test i used the code that posted #chmike as well.
Huge thanks to all of you guys for the help you provided :)

C Expected Output Failure [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 5 years ago.
Improve this question
Here is my program.I am trying to find the frequency of each character of a string and display it. While answering please see to it that I don't want to try the ASCII concept and I want to know whats wrong with this concept.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
int l=0,j,k,m,count[10000];
char string[10000];
printf("Enter the string : \n");
scanf("%s",string);
l=strlen(string);
printf("%d",l);
for(j=0;j<l;j++)
{
for(k=j+1;k<l;k++)
{
if(string[j]==string[k])
{
count[j]++;
}
}
}
for(m=0;m<l;m++)
{
printf("%d",count[m]);
}
return 0;
}
So you wish to find the frequency of characters in your string.
About the mistakes in your code:
Consider the string lalal Here you would be counting the last l twice, once corresponding to first l and second time corresponding to third l. Hence your logic is faulty.
Similar is the case of count[]. You haven't initialized the array hence it holds garbage values.
So another approach to your problem could be declaring a 26-element array(English alphabet), iterate through the entire list and increment count corresponding to each element when that element is found.
int frequencyChar[26] = {0};//stores frequency of characters [a-z], initialized to zero
for( i=0; i<strlen(str); i++) //iterate through the entire string
{
frequencyChar[str[i] - 'a']++; //increment count corresponding to each element
}
for( i=0; i<26; i++)
{
printf("%d\n",frequencyChar[i]);
}
P.S.Above code assumes only lowercase characters in string. Minor changes would allow inclusion of uppercase letters!
Here are the problems:
You have written: I am trying to find the frequency of each character, but you code is attempting to calculate histogram of correlations between pairs of characters.
as an index for count you are using j, which iterates over constitutive characters in string. This means that your table count have lots of 0 and only some 1 and nothing else.
So currently this is NOT histogram of pairs of characters nor histogram of characters.
Character histogram can be created like this:
void makeStrHistogram(char *str, int histogram[256])
{
memset(histogram, 0, sizeof(histogram));
while (*str) histogram[*str++]++;
}
void printHistogram(int histogram[256])
{
for (int i=0; i<256; ++i) {
if (histogram[i]) {
printf("%c - %d\n", (char)i, histogram[i]);
}
}
}
To generate character correlation matrix:
void correlationMatrixForStr(char *str, int matrix[256][256])
{
memset(matrix, 0, sizeof(matrix));
int len = strlen(str);
for (int i=0; i<len; ++i) {
for (int j=i+1; j<len; ++j) {
matrix[i][j]++;
}
}
}

Is there a way to print only the first word of a string with gets() in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am very new to programming and i wonder if there is a way to print out the first word of a string with gets() in C?
void printFirstWord(char string[])
{
int i;
for(i = 0; i < (string[i] != '\0'); i++)
{
if(isalpha(string[i]))
printf("%c", string[i]);
}
}
int main()
{
char string[MAX];
printf("Type in a scentence");
gets(string);
printFirstWord(string);
return 0;
}
This is the function that i have written and called in main right now. Is it because i have isalpha in the function?
In your implementation, you might add the following line in the loop:
if (string[i] == ' ')
break;
also, fix your loop parameters e.g. like this:
for (i = 0; i < strlen(string); i++)
Overall implementation in you way will be as below.
Consider choosing another design according to comments you got, e.g. not using gets.
void printFirstWord(char string[])
{
int i;
for (i = 0; i < strlen(string); i++)
{
if (isalpha(string[i]))
printf("%c", string[i]);
if (string[i] == ' ')
break;
}
}
int main()
{
#define MAX 100
char string[MAX];
printf("Type in a scentence\n");
gets_s(string, MAX);
printFirstWord(string);
getchar();
return 0;
}
I just found a way with isblank(); function, hope it helps to anybody :)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main (){
int length, number, counter, position;
char name[50];
printf("Please type your complete name:\n");
gets(name);
//strlen();
//Returns the length of the given null-terminated byte string, that is, the number of characters in a character array
length=strlen(name);
//Counts each position until it finds a space
for(counter=0;counter<length;counter++)
{
if(isblank(name[counter]))
position=counter;
}
//Prints each character until the counter reaches the position number given by the counter variable
printf("\nThe first word you typed is: ");
for(number=0; number<=position; number++){
printf("%c", name[number]);
}
}

Collecting same words in an array, C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 8 years ago.
Improve this question
If I had an array that looks like :
'A\t2\nB\t5\nC\t6\nB\t2\n' <- alphabet and numbers are separated by a tab(\t) and a new line(\n) after the number.
I need to collect the same alphabet together also summing the number behind of alphabet. If printing out the output should looks like:
'A\t2\nB\t7\nC\t6'.
I thought of using a strcmp function, but the input array may change so I wont be able to know what alphabet is in it.
edit: sorry, I think my question is not clear. My array is not only a character, but it can be a sequence of character+numbers too. such as: 'THIS\t25\nTHESE\t67\nTHOSE\t2\nTHESE\t102\nTHOSE23\t55\n'
You can read the current line's alphabet into char c and the number into int i and have a int alpha[26] defined with all entries initialised to 0. Then you just have to:
alpha[c - 'A'] += i;
then just print out all non-zero entries in alpha
You can collect each character at a time and use a switch to produce the desire output...
like...
getch(c);
switch(c)
{
//case for alphabets
//case for numbers
}
I think you should first find smallest letter (by ASCII code number ex. A=65), search input strings for this letter (maybe using strchr) and summ (in separate variable) all numbers relative to this letter, at the end, write letter and number in new string and proceed with next letter (B=66).
Then you'll have new string sorted and summarized.
char *input;
char *output;
char *p, *cur;
int nums, num;
char min;
char temp[20];
//search for minimal letter
for(int i = 0; i < strlen(input); i++){
if(input[i] > 65 && input[i] < 90)
if(input[i] < min)
min = input[i];
}
//parsing input string
for(int i = 0; i < strlen(input)/4; i++){
//strlen(input)/4 because each sequense at least 4 letters
p = input;
num = 0;
nums = 0;
while(cur = strchr(p, min)){
sscanf(cur+2, "%d", &num);
nums += num;
p = cur+1;
}
//filling new string
sprintf(temp, "%c\t%d\n", min, nums);
strcat(output, temp);
min++;
}

Resources