I want to write a program that works like this:
1: receives string1 and string2
2: compears the length of both to see which one is smaller
3: checks if the smaller string is used inside the bigger string
now I know how to write steps 1 and 2 but I don't have any idea how to solve step 3 :/
Here is my code so far:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
printf("Please enter string 1 size and then enter a text: ");
int size1;
scanf("%d", &size1);
char test1[size1];
scanf("%s", test1);
printf("Please enter string 2 size and then enter a text: ");
int size2;
scanf("%d", &size2);
char test2[size2];
scanf("%s", test2);
int test1_len = strlen(test1);
int test2_len = strlen(test2);
if (test1_len < test2_len)
{
//searching test1 in test2
}
else //(test1_len >= test2_len)
{
//searching test2 in test1
}
return 0;
}
CodePudding user response:
Applied answer from similar question: Simple way to check if a string contains another string in C? to the example provided.
Also added additional case of string lengths and content matching.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
printf("Please enter string 1 size and then enter a text: ");
int size1;
scanf("%d", &size1);
char test1[size1];
scanf("%S", test1);
printf("Please enter string 2 size and then enter a text: ");
int size2;
scanf("%d", &size2);
char test2[size2];
scanf("%S", test2);
int test1_len = strlen(test1);
int test2_len = strlen(test2);
if (test1_len < test2_len)
{
printf("String1 length is less than String2 length");
if (strstr(test2, test1) != NULL) {
printf("String1 is in String2");
}
else {
printf("String1 is not in string2");
}
}
else if (test1_len > test2_len)
{
printf("String2 length is less than String1 length");
if (strstr(test1, test2) != NULL) {
printf("String2 is in string1");
}
else {
printf("String2 is not in string1");
}
}
else
{
printf("String1 and String2 are same length");
if (strstr(test1, test2) != NULL) {
printf("String1 and String2 are the same");
}
else {
printf("String1 and String2 are not the same");
}
}
return 0;
}