using two-dimensional array for store several strings - c

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.

Related

why this program ends when i type the first word and doesn't loop back

i want to make the programm loop again and again until i type the endword ****TELOS
/* 1 */ int text_input();
int main() {
int number;
text_input();
return 0;
}
int text_input(char words[M][N]){
int l=0; /*lines, also how many words the text has */
char a;
int i=0;
printf("Enter the text. (****TELOS for stoping)");
char endword[10];
strcpy(endword, "****TELOS");
char temp[N];
while(1){
while(1) {
a = getchar();
if (a =='\n'){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else if (a == ' '){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else {
temp[i++] = a;
}
}
if (strcmp(temp, endword) == 0){
break;
}
else{
strcpy(words[l++],temp);
memset(temp, ' ', strlen(temp));
}
}
return 0;
}
I think your code doesn't work because you don't have set each item of endword to 0
so your code should be like that
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 10
#define M 10
int text_input(char words[M][N]);
int main() {
char a[M][N];
text_input(a);
return 0;
}
int text_input(char words[M][N]){
int l=0; /*lines, also how many words the text has */
char a;
int i=0;
char temp[N];
char endword[10] = {0,0,0,0,0,0,0,0,0,0};
printf("Enter the text. (****TELOS for stoping)");
strcpy(endword, "****TELOS");
while(1){
while(1) {
a = getchar();
if (a =='\n'){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else if (a == ' '){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else {
temp[i++] = a;
}
}
if (strcmp(temp, endword) == 0){
break;
}
else{
strcpy(words[l++],temp);
memset(temp, ' ', strlen(temp));
}
}
return 0;
}

Find specifi ID info using structure

I could not find specific student_Id info from a rage of given info.suppose, I am taking input from 1 to 100 all student info. now I want to find only 50th number student_ID all info.i could not do it. how it possible.here show my code. what's wrong with my code and how fixed it.thanks
# include <string.h>
# include <stdio.h>
# include <stdlib.h>
# include <conio.h>
struct student
{
char student_id[100];
char name[10];
int m[50],credit[100],sub[100];
int total,sumCredit;
float GP[100];
char result[5];
char grade[100][10];
double sumCreditxGP;
}*p,*s;
float gradesToGP(float marks);
char *markToG(float gp);
void lines(void);
void main()
{
int i,j,l,n,sub,k;
// clrscr();
printf("Enter the no. of students : ");
scanf("%d",&n);
p=(struct student*) malloc(n*sizeof(struct student));
//printf("%d",p);
//exit(0);
s=p;
for(i=0; i<n; i++)
{
printf("Enter a student id : ");
scanf("%s",&p->student_id);
printf("Enter a name : ");
scanf("%s",&p->name);
printf("Enter the no. of subject : ");
scanf("%d",&p->sub[i]);
p-> total=0;
p-> sumCredit=0;
p-> sumCreditxGP=0;
l=0;
for(j=0; j<p->sub[i]; j++)
{
one:
printf("Enter Marks of %d Subject\t%d : ",j+1,p->sub[i]);
scanf("%d",&p->m[j]);
printf("Enter Credit Hour: ");
scanf("%d",&p->credit[j]);
p->GP[j] = gradesToGP((float)p->m[j]);
strcpy(p->grade[j],markToG(p->m[j]));
if((p->m[j])>100)
{
printf("---------------Wrong Value Entered-----------\n");
goto one;
}
p->total+=p->m[j];
p->sumCredit+=p->credit[j];
p->sumCreditxGP+=p->credit[j]*p->GP[j];
if(p->m[j]<40)
l=1;
}
if(l==0)
strcpy(p->result,"PASS");
else
strcpy(p->result,"FAIL");
p++;
}
char search_id[10];
printf("Enter id to find specific student ");
scanf("%s",search_id);
//PROBLEM START HERE
for(i=0; i<n; i++)
{
if(p->student_id==search_id){
printf("found");
printf("%s",s->student_id);
}else{
printf("Not found");
}
s++;
}
getch();
}
float gradesToGP(float marks)
{
if (marks>=80 && marks<=100)
{
return(float)4.00;
}
else if (marks>=75 && marks<=79)
{
return(float)3.67;
}
else if (marks>=70 && marks<=74)
{
return(float)3.33;
}
else if (marks>=65 && marks<=69)
{
return(float)3.00;
}
else if (marks>=60 && marks<=64)
{
return(float)2.67;
}
else if (marks>=55 && marks<=59)
{
return(float)2.33;
}
else
{
return(float)5.00;
}
}
char *markToG(float marks)
{
if (marks>=80 && marks<=100)
{
return "A";
}
else if (marks>=75 && marks<=79)
{
return "A-";
}
else if (marks>=70 && marks<=74)
{
return "B+";
}
else if (marks>=65 && marks<=69)
{
return "B";
}
else if (marks>=60 && marks<=64)
{
return "B-";
}
else if (marks>=55 && marks<=59)
{
return "C+";
}
else
{
return "null";
}
}
void lines(void)
{ printf("**********************************************************************");
}
Please tell me how can I fixed it.thanks in advanced.
if(p->student_id==search_id){
printf("found");
Now, that's not how you compare strings in C. Use the strcmp() function for string comparison. You may read about strcmp() here.
The issue is your equality check: if(p->student_id==search_id)
Because both student_id and search_id are char arrays, the types will decay to pointers (char *) and this will never work as you expect. Instead, you need to use strcmp (or better, strncmp).
if(strncmp(p->student_id, search_id, 10) == 0) { /* equality */ }

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();
}

find one string in another string using 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;
}

Stack of strings

Hi i have program here that accept int as value. i wanted to translate it to accept strings in array then. i have read about using struct but i couldnt get into it. i hope someone can help me getting into that without using struct i dont know where to start i want to keep this lines of code.
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
int top = 0;
int *stack = NULL;
int size = 0;
main()
{
int opt, num;
char cont[] = { 'y' };
clrscr();
/* <start Declaring Stack Size { */
printf("Stacking Program");
printf("\n\nData Size: ");
scanf("%d", &size);
printf("\n");
/* } end> */
/* <start Allocates size of stack { */
if(size > 0)
{
stack = malloc(size * sizeof(int));
if(stack == NULL)
{
printf("ERROR: malloc() failed\n");
exit(2);
}
}
else
{
printf("ERROR: size should be positive integer\n");
exit(1);
}
/* } end> */
while((cont[0] == 'y') || (cont[0] == 'Y'))
{
clrscr();
/* <start Main Menu { */
printf("Stacking Program");
printf("\n\nData Size: %d\n\n", size);
printf("MAIN MENU\n1. Pop\n2. Push\n3. Pick\n4. View\nChoose: ");
scanf("%d", &opt);
printf("\n");
switch(opt) {
case 1:
pop();
break;
case 2:
if(top==size)
{
printf("You can't push more data");
}
else
{
printf("Enter data for Stack[%d]: ", top+1);
scanf("%d", &num);
push(num);
}
break;
case 3:
pick();
break;
case 4:
view();
break;
default:
printf("Your choice is not on the list.");
break;
}
/* } end> */
printf("\n\nDo you want continue\(Y\/N\)?");
scanf("%s", &cont[0]);
}
free(stack);
}
pop()
{
int a;
loading();
if(top <= 0)
{
printf("Stack empty.");
return 0;
}
else
{
top--;
a=stack[top];
printf("\(Stack[%d] = %d\) removed.", top+1, a);
}
}
push(int a)
{
stack[top]=a;
top++;
loading();
}
pick()
{
loading();
if(top <= 0)
{
printf("Nothing to display.");
return 0;
}
else
{
printf("\(Stack[%d] = %d\) is the last data.", top, stack[top-1]);
}
}
view()
{
int i;
loading();
if(top <= 0)
{
printf("Nothing to display.");
return 0;
}
else
{
for(i=0;i<top;i++)
{
printf("Stack[%d] = %d\n", i+1, stack[i]);
}
}
}
loading()
{
float i, x;
float load;
int loadarea[] = { 5000, 10000, 15000, 20000, 25000, 30000 };
int percentLoad;
x=0;
load=0;
percentLoad = loadarea[random(5)];
gotoxy(26,11);
printf("[");
for(i=0;i<25;i++)
{
x = i+27;
gotoxy(x, 11);
printf("=");
delay(percentLoad);
gotoxy(51,11);
printf("]");
gotoxy(53,11);
load=(i/25)*104.5;
if(load>100)
load = 100.00;
printf("%.2f\%",load);
}
delay(60000);
for(i=0;i<60;i++) {
printf("\b \b");
}
printf("\n");
}
Easiest way is to convert your stack to store char* instead of int.
char **stack;
stack = malloc( size * sizeof(char*) );
Now, your push operation will accept a char* from some buffer that is storing the string that was just input, duplicate it with strdup, and store that new pointer in the stack.
typedef enum {
STACK_MEM_ERROR = -1,
STACK_FULL = 0,
STACK_OK = 1
} StackStatus;
StackStatus push(const char *str)
{
char *newstr;
if( top >= size ) return STACK_FULL;
newstr = strdup(str);
if( newstr == NULL ) return STACK_MEM_ERROR;
stack[top++] = newstr;
return STACK_OK;
}
When you pop a string, you just get a pointer.
char *pop()
{
if( top == 0 ) return NULL;
return stack[--top];
}
You are responsible for freeing that memory when you are finished with the pointer (by calling free).
char * val;
while( NULL != (val = pop()) )
{
printf( "I popped: %s\n", val );
free(val);
}

Resources