0

write a function begins(string1, string2) that reurns true if string1 begins string2. Write a program to test the function. program:

#include<stdio.h>
#include<string.h>

char begins(char sentence1[],char sentence2[])
{
int i,j=0;

for(i=0;sentence1!='\0';++i)
{
if(sentence1==sentence2)
j=j+1;
else
if(j==i)
printf("True\n");
}

return(0);
}

int main()
{
int i, j=0;
char string1[100],string2[100];
printf("Enter a sentence:\n");
fgets(string1,sizeof(string1),stdin);
sscanf(string1,"%c",&string1);
printf("Enter a second sentence:\n");
fgets(string2,sizeof(string2),stdin);
sscanf(string2,"%c",&string2);
/*uses the function for the strings below*/
begins(string1,string2);
return(0);
}

i dont know what to do, theres something wrong with my function. Any help would be great. thanks!

2
Contributors
4
Replies
5
Views
12 Years
Discussion Span
Last Post by Alfy
0

How do you know that it doesn't work if you don't use the return value? :rolleyes: Try something like this:

int begins ( const char s1[], const char s2[] )
{
  int i;

  for ( i = 0; s1[i] != '\0'; i++ ) {
    if ( s1[i] != s2[i] )
      return 0;
  }

  return 1;
}

Of course, now (as if you didn't before) you have an issue where s2 might be shorter than s1, I'll leave that fix to you.

0

whats the reason for defining s1 and s2 as constants?

0

>whats the reason for defining s1 and s2 as constants?
Does the function modify either s1 or s2? No, so why not let the compiler tell you if you make a mistake and try to change either of them? It's surprisingly easy to type = instead of !=, you know. Why make programming harder than it already is? Are you a masochist? ;)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.