Reputation: 35
We have to write a program that would combine first letter alike in alphabetical order. E.G. input= Tea,boat,bee,toe,Baby. The output should be =Babybeeboat,Teatoe. But my program would print the same string twice before combining the words. Here's my code:
//how to combine first letter alike string
#include <stdio.h>
#include <string.h>
int main()
{
char str1[1000][1000], str[1000], temp[1000];
int n, i, p, j, a;
char *ptr, *ptr1;
printf("Enter how many arrays: ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Enter string %d: ", i+1);
scanf("%s", &str1[i]);
}
for(i=0; i<n; i++)
{
for(j=0; j<n-i-1; j++)
{
if(strcmp(str1[j], str1[j+1])>0)
{
strcpy(temp, str1[j]);
strcpy(str1[j], str1[j+1]);
strcpy(str1[j+1], temp);
}
}
}
for(i=0; i<n; i++)
{
for(j=0; j<i-1; j++)
{
a=strncmp(str1[j],str1[j+1],1);
if(a==0)
printf("%s", str1[j]);
else
printf(",");
}
}
for(i=0; i<n; i++)
{
for(j=0; j<i-1; j++)
{
a=strncmp(str1[j],str1[j+1],1);
if(a==0)
printf("%s", str1[i]);
else
printf(",");
}
}
}
Upvotes: 0
Views: 62
Reputation: 6494
You're going wrong in the last few for loops:
for(i=0; i<n; i++) { for(j=0; j<n-i-1; j++) {
The outer loop should stop at n-1 and the inner loop should start from i+1 (i.e. next string in array) to n:
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if(strcmp(str1[i], str1[j])>0)
{
strcpy(temp, str1[i]);
strcpy(str1[i], str1[j]);
strcpy(str1[j], temp);
}
}
}
Then you just need one loop after this that checks the first character of the strings in the array. If the character is different you print ,<string>
. Store the character for comparison in the next iteration.
char letter;
for(i=0; i<n; i++)
{
if (i != 0)
{
if (str1[i][0] != letter)
{
printf(",");
}
}
printf("%s", str1[i]);
letter = str1[i][0];
}
Upvotes: 1