CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Dec 2004
    Location
    Leamington Spa, UK
    Posts
    202

    "Special sting comparison"

    Greetings,

    I am trying to compare strings together in order to extract the common parts in them. For example, if one string is "Twinke twinkle little star" and the second string is "Twinke twinkle little car", I would like to get the similar section of them, which in this case is "Twinke twinkle little". CString.Compare() (which is the same as strcmp()) do not do that obviously. Does anybody know of an existing function somewhere that whould do the above, or at least return the number of characters that are similar?

    Thanks,

    Aristotel

  2. #2
    Join Date
    Apr 2005
    Location
    Norway
    Posts
    3,934

    Re: "Special sting comparison"

    You can start by searching google for "longest common substring".

    - petter

  3. #3
    Join Date
    Dec 2004
    Location
    Leamington Spa, UK
    Posts
    202

    Re: "Special sting comparison"

    Great..thanks...

    I was searching for "compare common strings." With "longest common substring", I get lots of results.


    Thanks!

  4. #4
    Join Date
    Apr 1999
    Posts
    3,585

    Re: "Special sting comparison"

    Give this a shot:

    Code:
    CString str("Twinkle twinkle little star");
    CString str2("Twinkle twinkle little car");
    CString res = str.SpanIncluding(str2);
    Note: you may have to strip trailing spaces.
    Gort...Klaatu, Barada Nikto!

  5. #5
    Join Date
    Nov 2000
    Location
    Voronezh, Russia
    Posts
    6,620

    Re: "Special sting comparison"

    Quote Originally Posted by greekgoddj
    I was searching for "compare common strings." With "longest common substring", I get lots of results.
    You'd have to try it yourself instead of inet punishing:

    Code:
    #include <windows.h>
    #include <atlstr.h>
    #include <stdio.h>
    
    CString str("Twinkle twinkle little star");
    CString str2("Twinkle twinkle little car");
    
    int main()
    {
        LPCTSTR p1 = str, p2 = str2;
        int idx;
    
    	for(idx = 0; *p1 && *p2; idx++)
    	{
    		if( *p1 != *p2 )
    			break;
    		++p1;
    		++p2;
    	}
    
    	CString longestSubstr = str.Left(idx);
    	printf("substr: \"%s\"\n", longestSubstr);
    }
    Best regards,
    Igor

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured