Thread: substrings

  1. #1
    ... arjunajay's Avatar
    Join Date
    May 2005
    Posts
    203

    Question substrings

    I just made a program which searches for subtrings from a char* the hard way.
    does someone have an algoritm which is better than this?
    here's my code...
    Code:
    #include<iostream.h>
    #include<conio.h>
    #include<string.h>
    #include<stdio.h>
    enum Bool{false, true};
    
    Bool search(char sub[], char sup[]){
    int subl=strlen(sub), supl=strlen(sup), st=0;
    Bool flag = false;
    if(supl<subl)return false;                  // sub larger than superstring.
    else{
    	for(int i=0; i<subl; i++)
    	for(int j=st; j<supl && i<subl; j++)
    		if(sub[i]==sup[j]){
    		flag = true;
    		i++;
    		}else{
    		flag = false;
    		i=-1;
    		st++;
    		break;
    		}
    	return flag;
    }
    }
    
    void main(){
    clrscr();
    char a[20], b[20];
    do{
    gets(a);
    gets(b);
    
    if( search(a, b) )cout<<"Substring !";
    else cout<<"Not substring !";
    cout<<"\n'q' to quit...\n\n\n";
    }while( getch()!='q' );
    getch();
    }
    This code is like noodles;
    Even I can't make out the head or tail of it now.
    P.S. I dont want to use any standard 'String' class or anything.
    Last edited by arjunajay; 06-01-2005 at 05:08 AM. Reason: nedd to append.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > does someone have an algoritm which is better than this?
    Yes, but until you get past the "void main" and "gets(a)" problems, there isn't much point explaining.

    Also, you really need to use the preview button - Half your code is lost in italics.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    ... arjunajay's Avatar
    Join Date
    May 2005
    Posts
    203

    Angry Serious

    Why do you hate 'void main()' and 'gets()'?
    Does someone pay you?
    I use void since I'm not returning any value.
    Is'nt that the standard?
    And the italics might be some typo.
    I copied and pasted.
    And Ifound the reason for italics...
    its the subscript thingi with 'i' inside.
    I don't know the correction.
    Last edited by arjunajay; 06-01-2005 at 06:46 AM. Reason: Typo

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    4
    Main has to return due to compatibility issues. E.G so external programs can check if it exited successfully or not.

    Also gets() is unsafe because it can be used to cause a buffer overflow.

    Id use cin.getline()
    Last edited by Robn; 06-01-2005 at 07:25 AM.

  5. #5
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Quote Originally Posted by arjunajay
    I just made a program which searches for subtrings from a char* the hard way.
    Really? Did you write it in C or C++?
    Code:
    C++ Code
    //good ole i/o streams
    cout << "Substring !";
    Code:
    C Code
    //strange boolean enumeration
    enum Bool{false, true};
    Code:
    Bad C++ Code
    //.h headers are deprecated
    //use <iostream> and the std namespace
    #include<iostream.h>
    Code:
    Bad C Code
    //use fgets
    gets(a);
    Code:
    Just Plain Wrong Code
    //use int main
    void main()
    Quote Originally Posted by arjunajay
    This code is like noodles; Even I can't make out the head or tail of it now.
    If you wrote it, surely you remember the logic of what you did. Explain to us the logic of your algorithm.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Why do you hate 'void main()' and 'gets()'?
    Because void main is wrong and gets is unsafe. Why do you like 'void main()' and 'gets()'?

    >I use void since I'm not returning any value.
    Yet the standard requires main to return an int value in all cases. And since 0 is returned by default if you fall of the end of main with a modern compiler, you have no excuse for using void main. The following is valid C++:
    Code:
    int main()
    {
    }
    However, this is not valid C++ unless your compiler allows it as a non-portable extension:
    Code:
    void main()
    {
    }
    Therefore, int main requires less typing than void main on a conforming compiler, so only stubborn and ignorant people would use void main[1].

    >Is'nt that the standard?
    No, and it never has been, even as far back as K&R C. main has always returned int, and the standards reflect that history.


    [1] Assuming a hosted implementation. On a freestanding implementation, there are no restrictions for main because it's not bound by the runtime environment. However, if you're on a freestanding implementation, you likely wouldn't be asking us for help.
    My best code is written with the delete key.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > Why do you hate 'void main()' and 'gets()'?
    Because they're flat out wrong.
    "Works for me" is no defence when someone shows up at your door with a buffer overflow problem caused by your sloppy coding. Either learn to do it properly, or just get out of programming.

    > Does someone pay you?
    Yes, I get paid quite well thanks, for being a pretty damn good programmer who doesn't make loads of rubbish mistakes which need expensive fixing later on.
    If you ever want to get a job, you can be pretty sure of lots of rejections if you fail to recognise these as common programming pitfalls at the interview.

    > I use void since I'm not returning any value.
    It's not up to you - the environment wants a value whether you feel like returning anything or not. If you have nothing to return, then a simple
    return 0;
    is all you need. How hard is that?

    > Is'nt that the standard?
    No. void main has never been the standard, and using gets() is just plain dumb.
    I can tell that you've never read the FAQ.

    > And the italics might be some typo.
    Yeah, unfortunately, a subscript of i matches the italics tag.
    Simply putting a space in there should fix it.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    ... arjunajay's Avatar
    Join Date
    May 2005
    Posts
    203

    Unhappy Don't ATTACK me :(

    Thanks for all the replies.
    But I never found what I wanted...
    and about the correction for my c++ code...
    My compiler is some pre-standard thingi.
    I tried to download both Borland and GCC and Microsoft C++ compilers so that i can start using standrad C++.
    But I nearly fainted when the down load times showed 6 to 23 hours. My phone bill would not just skyrocket; but it will cross light speed and be thrown back in time(???).

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    http://www.bloodshed.net/dev/devcpp.html
    How long would it take you to d/l 9MB?

    Be creative - look for copies of compilers on CD's which come with magazines, find a friend with a better IP connection and a CD burner.
    Or maybe there's some local tech company would be willing to help you out. If you keep in contact with them, it'll look good at job finding time.
    Or the local library....

    > My compiler is some pre-standard thingi.
    Yeah, so it's really not the best idea to learn a bunch of outdated stuff, only to have to unlearn it again later on.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >But I never found what I wanted...
    Code:
    const char *substr(const char *s, const char *match)
    {
      do {
        const char *p, *q;
    
        for (p = s, q = match; *p == *q; p++, q++)
          ;
        if (*q == '\0')
          return s;
      } while (*s++ != '\0');
    
      return 0;
    }
    There are better string search algorithms, but this (in whatever form you care to present it) is the simplest.
    My best code is written with the delete key.

  11. #11
    ... arjunajay's Avatar
    Join Date
    May 2005
    Posts
    203

    Smile Thanks

    Thanks for the code.
    I'll figure it out.
    I did'nt figure it could be this small.

  12. #12
    Registered User
    Join Date
    Jun 2004
    Posts
    722
    Code:
    const char *substr(const char *s, const char *match)
    {
      do {
        const char *p, *q;
        //if both strings match it'll end up comparing chars after the string's end
        for (p = s, q = match; *p == *q && *q!=0 ; p++, q++)
          ;
        if (*q == '\0')
          return s;
      } while (++*s != '\0');//i think we want to know if the next char is valid, not the actual
    
      return 0;
    }
    Did I just try to fix Prelude's code ?!?
    Last edited by xErath; 06-02-2005 at 07:42 PM.

  13. #13
    ... arjunajay's Avatar
    Join Date
    May 2005
    Posts
    203

    Smile Thnks again...

    title.

  14. #14
    ... arjunajay's Avatar
    Join Date
    May 2005
    Posts
    203

    Exclamation error

    Thanks for the correction but it gave an error at:
    Code:
    }while(++*s != '\0');
    it was "cannot modify a constant object."
    so I changed it to :
    Code:
    }while(*(++s) != '\0');
    and it woked just fine. .
    Thanks again !!!

  15. #15
    Registered User
    Join Date
    Jun 2004
    Posts
    722
    yeap :P it's a const char, and since ++ has precendence equal to *, ++*s will try to increment *s, but *(s++) will increment the pointer. just a small error :P
    http://www.cppreference.com/operator_precedence.html

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help, extracting substrings from a string
    By doubty in forum C Programming
    Replies: 1
    Last Post: 06-17-2009, 11:57 PM
  2. Need help on substrings and streams
    By TaiL in forum C++ Programming
    Replies: 2
    Last Post: 10-08-2008, 06:18 PM
  3. vector of substrings
    By manav in forum C++ Programming
    Replies: 47
    Last Post: 05-10-2008, 02:05 PM
  4. Searching for a series of possible substrings inside a string
    By andrew.bolster in forum C Programming
    Replies: 7
    Last Post: 02-10-2008, 02:20 AM
  5. Searching strings - substring's
    By Vber in forum C Programming
    Replies: 4
    Last Post: 02-06-2003, 12:05 PM