find one string in another string using c - c

I have written following code to find str1 is present in str2 or not. But it doesn't work all scenarios.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i,j,flag=1;
char str1[]="goa",str2[]="gogoa";
if (strlen(str1)>strlen(str2))
{
printf("not found");
return;
}
for ( i = 0; str2[i]; i++)
{
if (str1[0]==str2[i])
{
for ( j = 0; str1[j]; j++)
{
if (str1[j]!=str2[i+j])
{
printf("not found");
flag=0;
}
}
break;
}
}
if (flag==1)
{
printf("found at index %d ",i);
}
getchar();
}
its not working when str1 starting character is present multiple times in str2,otherwise it works fine.
How can I optimize this to make it work in all scenarios?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
int i, j, flag=0, len1, len2;
char str1[]="goa",str2[]="gogoa";
len1 = strlen(str1);
len2 = strlen(str2);
if (len1 > len2){
printf("not found");
return 0;
}
for (i = 0; i <= len2 - len1; ++i){
if (str1[0]==str2[i]){
flag = 1;
for (j = 1; str1[j]; ++j){
if (str1[j]!=str2[i+j]){
flag=0;
break;
}
}
if(flag==1)
break;
}
}
if (flag==1){
printf("found at index %d ",i);
} else {
printf("not found");
}
return 0;
}

try this:
int i,j,flag=0, match=0;
char str1[]="goa",str2[]="gogoa";
if (strlen(str1)>strlen(str2))
{
printf("not found");
return;
}
for ( i = 0; str2[i]; i++)
{
if (str1[0]==str2[i])
{
match=1;
for ( j = 0; str1[j]; j++)
{
if (str1[j]!=str2[i+j])
match=0;
}
if(match == 1)
{
flag = 1;
break;
}
}
}
if (flag==1)
printf("found at index %d ",i);
else
printf("not found");

I agree to comments that you should show what you have done. Please do that next time.
For now, I would like to suggest two approaches to debug out of sticky problems: use printfs and understand the flow OR use gdb. I have commented your program w.r.t. the printf approach. Have not tested all cases...but this should hopefully give you a direction to your debugging. Hope it helps. Remember to do this step before you post a question next time :-)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
int i,j,flag=1;
char str1[]="goa",str2[]="gogoa";
if (strlen(str1)>strlen(str2)) {
printf("not found");
return;
}
for ( i = 0; str2[i]; i++) {
/* If starting letter does not match, forget it */
if (str1[0]==str2[i]) {
flag = 1;
// Iterate thro' str1
for ( j = 0; str1[j]; j++) {
if (str1[j] != str2[i+j]) {
printf("%s not found at index %d of %s\n", str1, i, str2);
flag=0;
break; // out of inner for loop
}
}
if (j == strlen(str1)) {
// found the entire string.
break; // out of outer for loop
}
}
}
if (flag==1) {
printf("%s found at index %d of %s\n", str1, i, str2);
}
getchar();
}

I have rewritten the code with slight modifications in it and it's working for me,
check all your necessary scenarios, and let me know.
public static bool findString(string searchText, string fullText)
{
bool result = false;
if (searchText.Length > fullText.Length)
{
return false;
}
for (int i = 0; i <= (fullText.Length - searchText.Length); i++)
{
if (searchText[0] == fullText[i])
{
for (int j=0; j<searchText.Length ;j++)
{
if ((i+j)< fullText.Length && searchText[j] == fullText[i+j])
result = true;
else
{
result = false;
break;
}
}
}
if (result)
{
Console.WriteLine("found at index {0}", i);
break;
}
}
return result;
}
Sorry about the syntax, I only had c# available. you'll have to use strlen(string) for lengths and '%d' for '{0}', printf for Console.Writeline(" ");

#include <string.h>
if(strstr(str2, str1) != NULL) {
/* ... */
}
Please checkout the doc of strstr function.

//Declaration: char *strstr(const char *str1, const char *str2);
//Return: It returns a null pointer if no match is found.
#include <string.h>
#include <stdio.h>
int main(void)
{
char *p;
p = strstr("goa", "gogoa");
printf(p);
return 0;
}

Related

Print the correct Morse code for alpha entry

I now need to output the Morse code equivalent of alphanumeric input. My condition for check this is an if loop: I try to look at each element of input array with each element of the alpha array but a match never seems to be found. I am not sure if I am using the correct method. I try to de-reference the point to input and compare the value with each element of alpha until a match is found. If no match is found then an error occurs.
Not working:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
int main(void)
{
char *morse[] = {"/",
".-","-...","-.-.","-..",".","..-.","--","....","..",".---",
"-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
"..-","...-",".--","-..-","-.--","--..",
"-----",".----","..---","...--","....-",".....","-....","--...","---..","----."};
char *alpha[]= {" ",
"A","B","C","D","E","F","G","H","I","J",
"K","L","M","N","O","P","Q","R","S","T",
"U","V","W","X","Y", "Z",
"0", "1","2","3","4","5","6","7","8","9"};
char *print_array[50];
int print_array_index = 0;
char hold[50];
int hold_index = 0;
char input[200];
int i = 0;
printf("welcome to the Morse translator.\n");
printf("Enter input: ");
fgets(input, sizeof(input), stdin);
char *p;
for (p=input; *p !='\0';++p)
{
*p = toupper(*p);
}
if (input[0]=='-' || input[0]=='.')
{
while (input[i] !='\0') {
if (input[i] ==' ' || input[i] == '\n')
{
hold[hold_index] = '\0';
bool found = false;
for (int x = 0; x < sizeof(morse) / sizeof(char *); x++)
{
if (strcmp(morse[x], hold) == 0)
{
print_array[print_array_index++] = alpha[x];
found = true;
break;
}
}
if (!found)
{
fprintf(stderr, "invalid Morse code!\n");
}
hold_index = 0;
}
else
{
hold[hold_index++] = input[i];
}
i++;
}
for (int x = 0; x < print_array_index; x++)
{
printf("%s", print_array[x]);
}
printf("\n");
}
else if (isalnum(input[0]))
{
while (input[i]!='\0')
{
if (input[i] ==' ' || input[i] == '\n')
{
bool found = false;
for (int x=0; x < sizeof(alpha)/sizeof (char*);x++)
{
if (alpha[x]==input[i])
{
print_array [print_array_index++] = alpha[x];
found = true;
break;
}
}
if (!found)
{
fprintf(stderr, "Invalid input!\n");
}
hold_index = 0;
}
i++;
}
for (int x=0; x < print_array_index; x++)
{
printf("%s",print_array[x]);
}
printf("\n");
}
return 0;
}
part of else if (isalnum(input[0])){ should be something like
else if (isalnum(input[0])){
while (input[i]!='\0' && input[i]!='\n'){
bool found = false;
for (int x=0; x < sizeof(alpha)/sizeof(char*);x++){
if (*alpha[x]==input[i]){
print_array[print_array_index++] = morse[x];
found = true;
break;
}
}
if(!found){
fprintf(stderr, "Invalid input!\n");
}
i++;
}
for (int x=0; x < print_array_index; x++){
printf("%s", print_array[x]);
}
printf("\n");
}

Finding substring in string without using library function

Below is the code template and under /* write your code here */ is my own code.
The template should be correct but there is sth wrong with my code.
My algorithm is to iterate through str until finding the null character.
Then compare each character, if they are the same then iterate through both str and sub, otherwise set continue to iterate through str and reset to the first character of substr.
#include <stdio.h>
int findSubstring(char *str, char *substring);
int main()
{
char str[40], substr[40];
printf("Enter the string: ");
gets(str);
printf("Enter the substring: ");
gets(substr);
printf("findSubstring(): %d\n", findSubstring(str, substr));
return 0;
}
int findSubstring(char *str, char *substr)
{
/* write your code here */
int i = 0, j = 0;
while ((str[j] != '\0')||(substr[i] != '\0')) {
if (substr[i] != str[j]) {
j++;
i = 0;
}
else {
i++;
j++;
}
}
if (substr[i] == '\0')
return 1;
else
return -1;
}
Do not use gets(), which has unavoidable risk of buffer overrun.
The condition of the loop is wrong. The loop should exited if one of *(str + j) or *(substr + i) is a (terminating) null character.
Fixed code:
#include <stdio.h>
int findSubstring(char *str, char *substring);
void safer_gets(char *str, size_t max);
int main(void)
{
char str[40], substr[40];
printf("Enter the string: ");
safer_gets(str, sizeof(str));
printf("Enter the substring: ");
safer_gets(substr, sizeof(str));
printf("findSubstring(): %d\n", findSubstring(str, substr));
return 0;
}
int findSubstring(char *str, char *substr)
{
int i = 0, j = 0;
while ((*(str + j) != '\0')&&(*(substr + i) != '\0')) {
if (*(substr + i) != *(str + j)) {
j++;
i = 0;
}
else {
i++;
j++;
}
}
if (*(substr + i) == '\0')
return 1;
else
return -1;
}
void safer_gets(char *str, size_t max)
{
int i;
fgets(str, max, stdin);
for (i = 0; *(str + i) != '\0'; i++) {
if (*(str + i) == '\n') {
*(str + i) = '\0';
break;
}
}
}
/*--------------------------One more simple example-----------------------------
Find the words from a set of words containing a given substring?
Input: Set of Words: [blackcat, blackdog, blackrat, whitetiger, blueelephant],
Substring: black
Output:[blackcat, blackdog, blackrat]
-----------------------------------------------------------------------------------------*/
#include <iostream>
#include <cstring>
int substring(char* sub,char* string);
int main()
{
const char* Names[] { "blackcat", "blackdog", "blackrat", "whitetiger", "blueelephant" };
char substr[]{ "black" };
int found{ -1 };
for (auto strings: Names)
{
found = substring(substr, const_cast<char*>(strings));
if (found != -1) {
std::cout << strings << " ";
}
}
std::cout << std::endl;
return 0;
}
int substring(char* sub, char* string)
{
int i{};
int j{};
while ((string[i] != '\0') && (sub[j] != '\0'))
{
if (string[i] != sub[j]) {
j++;
i = 0;
}
else {
i++;
j++;
}
}
if (sub[j] == '\0' && i != 0) {
return 1;
}
else {
return -1;
}
}
#include<stdio.h>
#include<conio.h>
void main()
{
char s[100],sub[50];
int i,j,c=0;
clrscr();
printf("enter string and substring\n");
gets(s);
printf("\n");
gets(sub);
printf("\n");
i=0;
j=0;
while(s[i]!='\0')
{
if(s[i]!=sub[j])
i++;
else if(s[i]==sub[j])
{
while(sub[j]!='\0')
{
if(s[i]==sub[j])
{
i++;
j++;
c++;
}
else
{
c=0;
break;
}
}
}
}
if(c!=0)
printf("\nsubstring is present \n ");
else
printf("\nsubstring is absent \n ");
getch();
}

Program stuck in cycle

I'm trying to implement a C program for CRC for my laboratory exam. I've written the following code. But, it is same as the main source code but it got stuck at strcpy(). I can't figure it out. Here's the source code:
#include <stdio.h>
#include <string.h>
int ctoi(char a) {
return (a-48);
}
char itoc(int a) {
return (a+48);
}
void main() {
int ld, lm, i, j;
char div[20], ip[100], ipm[100], crc[10], snd[100]={0}, rcv[100];
printf("\t\t\tCRC Encoding\n");
printf("Enter the codeword: ");
scanf("%s",ip);
printf("Enter the divisor: ");
scanf("%s",div);
strcpy(ipm, ip);
lm = strlen(ipm);
ld = strlen(div);
if(lm>=ld) {
//padding
for(i=lm, j=0; j<ld-1; j++)
ipm[i++] = '0';
ipm[i] = '\0';
printf("Data word after appending zeroes: %s\n", ipm);
for(i=0;i<ld;i++)
crc[i] = ipm[i];
crc[i] = '\0';
for(;i<strlen(ipm);i++) {
if(crc[0] == '1') {
for(j=0; j<ld; j++)
crc[j] = itoc((ctoi(crc[j])) ^ (ctoi(div[j])));
}
crc[ld] = ipm[i];
crc[ld+1] = '\0';
for(j=0;crc[j]!='\0';j++)
crc[j] = crc[j+1];
crc[j] = '\0';
}
for(j=0;crc[j]!='\0';j++)
crc[j] = crc[j+1];
crc[j] = '\0';
printf("CRC remainder is: %s\n",crc);
strcat(snd, ip);
strcat(snd, crc);
printf("Sent codeword: %s\n",snd);
printf("CRC Decoding\n");
strcpy(rcv, snd);
printf("after strcpy");
printf("Received codeword: %s", rcv);
for(i=0;i<ld;i++) {
crc[i] = rcv[i];
}
crc[i] = '\0';
for( ;i<strlen(rcv);i++) {
if(crc[0]=='1') {
for(j=0;j<ld;j++) {
crc[j] = itoc((ctoi(crc[j])) ^ (ctoi(div[j])));
}
}
crc[ld] = rcv[i];
crc[ld+1] = '\0';
for (j = 0; crc[j]!='\0'; i++) {
crc[j] = crc[j+1];
}
crc[j] = '\0';
for(j=0; crc[j]!='\0'; j++) {
if(crc[j]!='0')
break;
}
printf("CRC remainder is: %s\n",crc);
if(j==strlen(crc)) {
printf("Received message is error free\n");
} else {
printf("Received message contains errors\n");
}
}
} else {
printf("Enter a proper divisor");
}
}
And the output screen is:
CRC Encoding
Enter the codeword: 10110
Enter the divisor: 110
Data word after appending zeroes: 1011000
CRC remainder is: 00
Sent codeword: 1011000
CRC Decoding
It is stuck at the above line. But the correct program is here:
#include<stdio.h>
#include<string.h>
int ctoi(char a)
{
return(a-48);
}
char itoc(int a)
{
return(a+48);
}
void main()
{
char ip[100],ipm[100],div[20],crc[10],sent[100]={0},rec[100];
int i,lm,ld,j;
printf("\nCRC encoding");
printf("\nEnter data word(message)");
scanf("%s",ip);
printf("\nEnter the divisor");
scanf("%s",div);
strcpy(ipm,ip);
lm=strlen(ipm);
ld=strlen(div);
if(lm>=ld)
{
for(i=lm,j=0;j<ld-1;j++)
ipm[i++]='0';
ipm[i]='\0';
printf("\nData word after appending zeros:%s",ipm);
for(i=0;i<ld;i++)
crc[i]=ipm[i];
crc[i]='\0';
for(;i<strlen(ipm);i++)
{
if(crc[0]=='1')
{ for(j=0;j<ld;j++)
{
crc[j]=itoc((ctoi(crc[j]))^(ctoi(div[j])));
}
}
crc[ld]=ipm[i];
crc[ld+1]='\0';
for(j=0;crc[j]!='\0';j++)
crc[j]=crc[j+1];
crc[j]='\0';
}
for(j=0;crc[j]!='\0';j++)
crc[j]=crc[j+1];
crc[j]='\0';
printf("\nCRC remainder is:%s",crc);
strcat(sent,ip);
strcat(sent,crc);
printf("\nCode word in sender side is:%s",sent);
printf("\nCRC decoing");
strcpy(rec,sent);
//rec[2]='1';
printf("\nReceived message in receiver side is :%s",rec);
for(i=0;i<ld;i++)
crc[i]=rec[i];
crc[i]='\0';
for(;i<strlen(rec);i++)
{
if(crc[0]=='1')
{
for(j=0;j<ld;j++)
{
crc[j]=itoc((ctoi(crc[j]))^(ctoi(div[j])));
}
}crc[ld]=rec[i];
crc[ld+1]='\0';
for(j=0;crc[j]!='\0';j++)
crc[j]=crc[j+1];
crc[j]='\0'; }
for(j=0;crc[j+1]!='\0';j++)
crc[j]=crc[j+1];
crc[j]='\0';
for(j=0;crc[j]!='\0';j++)
{
if(crc[j]!='0')
break;
}
printf("\nCRC remainder is:%s",crc);
if(j==strlen(crc))
printf("\nReceived message is error free!\n\n");
else
printf("\nError in received message!!!\n\n");
}
else
printf("\nEnter proper divisor");
}
And it runs perfect. I can't able to find the difference between these two programs even though I went through line by line. Can you tell me what's wrong with the first program?
The problem arises from a small typo in your code. You wrote
for (j = 0; crc[j]!='\0'; i++) {
crc[j] = crc[j+1];
}
but it should have been
for (j = 0; crc[j]!='\0'; j++) {
crc[j] = crc[j+1];
}
Mind the j++. Of course, the call to strcpy() is no culprit!

Sort numbers (underscore)

I am trying to fix my last problem and still, I cannot figure out how to solve it. My task was to write a program which sort numbers, but: our tutor gives us some extra points for program dealing with numbers like: 000054667 (in fact 54667) and 345_845 (in fact 345845). The first problem is already solved but I have no idea how to handle with the second one. Hence, my question is: do you have any tips/clue, which might help me? I am also sending my code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NUMBER_CHUNK 13
char* getNumber(FILE* fp)
{
int length, c;
int current=0;
char *number;
number=(char*)malloc(sizeof(char)*NUMBER_CHUNK);
if(!number)
{
printf("Error while alocating memory!\n");
return NULL;
}
length=NUMBER_CHUNK;
while(!isspace(c=fgetc(fp)) && !feof(fp))
{
if(isdigit(c))
{
number[current]=c;
current++;
if(current>=length)
{
length+=NUMBER_CHUNK;
if((number=((char*)realloc(number,sizeof(char*)*length)))==NULL)
{
free(number);
return NULL;
}
}
}
else
{
return NULL;
}
}
number[current]='\0';
return number;
}
int compare( const void *str1, const void *str2)
{
int value;
char* curr1;
char* curr2;
curr1=*(char**)str1;
curr2=*(char**)str2;
while(*curr1=='0') curr1++;
while(*curr2=='0') curr2++;
if(strlen(curr1) < strlen(curr2)) return -1;
if(strlen(curr1) > strlen(curr2)) return 1;
value=strcmp(curr1, curr2);
return value;
}
int main(int argc, char** argv)
{
FILE* fp;
char** tab;
int i=0;
int lines=0;
int length=10;
if(argc!=2)
{
printf("Incorrent syntax! Use ./name_of_program input_file\n");
return 1;
}
if(!(fp=fopen(argv[1],"r")))
{
printf("Could not open the file! Please try again!\n");
return 2;
}
tab = (char**)malloc(length*(sizeof(char*)));
if(!tab)
{
printf("Could not allocate memory! Terminating...\n");
free(tab);
return 3;
}
while(!feof(fp))
{
tab[i]=getNumber(fp);
if(i>=length)
{
length+=10;
if((tab=((char**)realloc(tab,sizeof(char*)*length)))==NULL)
{
free(tab);
return 5;
}
}
if(tab[i]==NULL)
{
printf("Incorrect character in the infile! Terminating\n");
free(tab);
return 4;
}
if(*tab[i]=='\0')
{
free(tab[i]);
i--;
}
i++;
lines++;
lines=i;
}
printf("\nBEFORE\n");
for(i=0;i<lines;i++)
{
printf("%s\n",tab[i]);
}
qsort(tab, lines, sizeof(char*), &compare);
printf("\nAFTER\n");
for(i=0;i<lines;i++)
{
printf("%s\n",tab[i]);
free(tab[i]);
}
free(tab);
fclose(fp);
return 0;
}
Thank you for any help ;)
Change string accumulation and your compare routine.
String accumulation:
if(isdigit(c) || (c == '_'))
Compare. This is a bit lengthy to incorporate ignoring _ for value ratings. But it is not limited to numbers that fit in any int range.
int compare(const void *str1, const void *str2) {
const char* curr1 = *(const char**) str1;
const char* curr2 = *(const char**) str2;
// Remove leading zeros
while ((*curr1 == '0') || (*curr1 == '_'))
curr1++;
while ((*curr2 == '0') || (*curr2 == '_'))
curr2++;
int value = 0;
size_t len1 = 0;
size_t len2 = 0;
while (*curr1 || *curr2) {
while (*curr1 == '_')
curr1++;
while (*curr2 == '_')
curr2++;
// If a difference has not been found yet ...
if (value == 0) {
value = *curr1 - *curr2;
}
if (*curr1) {
curr1++;
len1++;
}
if (*curr2) {
curr2++;
len2++;
}
}
// If significant digits in string1 more than string2 ...
if (len1 != len2) {
return (len1 > len2) ? 1 : -1;
}
return value;
}
Just keep parsing the string until you get an underscore, and with parsing also convert each character into the respective number and keep adding it to a new number according to it's place value (In a nutshell i'm speaking of an algorithm to convert string to numbers). and if you encounter an underscore, just use
continue;
If you want to retain the string representation for your "numbers" but compare them according to their numerical value, don't compare them as strings inside your compare function.
Inside compare parse each arguments (str1 and str2) and convert them to numbers skipping leading zeros and underscores. Once you have two numbers (say num1 and num2) just return num1 - num2.
Instead of storing a bunch of strings, you would be better off converting the numbers to ints by stripping out any non-digit characters and calling atoi on the results. You can store those numbers directly in the array. The compare function then becomes much simpler.
chux THX. You're brilliant! I wish I would be as good as you in programming.
I am sending my whole (fixed, working) source code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NUMBER_CHUNK 13
char* getNumber(FILE* fp)
{
int length;
int current = 0;
int c;
char *number, *number2;
number = (char*)malloc(sizeof(char)*NUMBER_CHUNK);
if(!number)
{
printf("Error while allocating memory!\n");
return NULL;
}
length = NUMBER_CHUNK;
while(!isspace(c = fgetc(fp)) && !feof(fp))
{
if(isdigit(c) || c == '_')
{
number[current] = c;
current++;
if(current >= length)
{
length+=NUMBER_CHUNK;
number2 = (char*)realloc(number,length*sizeof(char*));
if(number2 == NULL)
{
free(number2);
return NULL;
}
else number2 = number;
}
}
else
{
return NULL;
}
}
number[current] = '\0';
return number;
}
int compare(const void *str1, const void *str2)
{
char* curr1;
char* curr2;
curr1=*(char**)str1;
curr2=*(char**)str2;
while(*curr1=='0' || *curr1=='_') curr1++;
while(*curr2=='0' || *curr2=='_') curr2++;
int value = 0;
size_t len1 = 0;
size_t len2 = 0;
while(*curr1 || *curr2)
{
while(*curr1 == '_')
curr1++;
while(*curr2 == '_')
curr2++;
if(value == 0)
{
value = *curr1 - *curr2;
}
if(*curr1)
{
curr1++;
len1++;
}
if(*curr2)
{
curr2++;
len2++;
}
}
if(len1 != len2)
{
return (len1 > len2) ? 1 : -1;
}
return value;
}
int main(int argc, char** argv)
{
FILE* fp;
char** tab;
int i = 0;
int lines = 0;
int length = 10;
if(argc != 2)
{
printf("Incorrent syntax! Use ./name_of_program input_file\n");
return 1;
}
if(!(fp = fopen(argv[1],"r")))
{
printf("Could not open the file! Please try again!\n");
return 2;
}
tab = (char**)malloc(length*(sizeof(char*)));
if(!tab)
{
printf("Could not allocate memory!\n");
free(tab);
return 3;
}
while(!feof(fp))
{
tab[i] = getNumber(fp);
if(i >= length)
{
length += 10;
tab = (char**)realloc(tab,sizeof(char*));
if(tab == NULL)
{
free(tab);
return 5;
}
}
if(tab[i] == NULL)
{
printf("Incorrect character in the infile! Terminating\n");
free(tab);
return 4;
}
if(*tab[i] == '\0')
{
free(tab[i]);
i--;
}
i++;
lines = i;
}
printf("\nBEFORE\n");
for(i = 0 ; i < lines; i++)
{
printf("%s\n", tab[i]);
}
qsort(tab, lines, sizeof(char*), compare);
printf("\nAFTER\n");
for(i = 0; i < lines; i++)
{
printf("%s\n",tab[i]);
free(tab[i]);
}
printf("\n");
free(tab);
fclose(fp);
return 0;
}

using two-dimensional array for store several strings

I wrote a function in C that search if a substring is in a string and it's OK, but when I use it in a array of strings I face an error. Please see this code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int substring(char*, char*);
main()
{
char student[100][7];
int counter = 0;
int finish =1;
char s1[4];
while(finish){
printf("please Enter Student Number: \n");
scanf("%s", student[counter]);
counter++;
printf("Do you want to exit? 1/0");
scanf("%d", &finish);
}
printf("Now, You can search in Student numbers\n");
printf("Enter a number to search: ");
scanf("%s", s1);
for(int i = 0; i < counter; i++){
printf("%d : %s\n", i, student[i]);
if(substring(student[i],s1) == 1)
printf("%s", student[i]);
}
getch();
}
int substring(char *s1,char *s2)
{
int f=0;
for(; *s1 !='\0';)
{
if(*s2=='\0')
break;
for(;*s2 !='\0';)
{
if(*s1==*s2)
{
f=1;
s1 ++;
s2 ++;
}
else
{
f=0;
s1++;
break;
}
}
}
if(f==0)
return 0;
else
return 1;
getch();
}
This is how you can test for substring using simple state machine:
int substring(const char *s1, const char *s2)
{
enum
{
search, start_match
} state = search;
const char *m;
while(*s1 != '\0')
{
switch(state)
{
case search:
if(*s2 == '\0')
return 0;
else if(*s2 == *s1)
{
state = start_match;
m = s2 + 1;
}
break;
case start_match:
if(*m == '\0')
return 1;
else if(*m != *s1)
state = search;
else
++m;
}
++s1;
}
return 0;
}
Also you may use the standard strstr function.

Resources