View Single Post
Old Feb 17th, 2006, 12:23 AM   #13
titaniumdecoy
Expert Programmer
 
titaniumdecoy's Avatar
 
Join Date: Nov 2005
Posts: 856
Rep Power: 3 titaniumdecoy is on a distinguished road
Send a message via AIM to titaniumdecoy
Lucky for you, I'm practicing writing this type of data processing program before I major in CS next year. I am also learning C++, and this is the first full program I have written in the language.

If this is a school assignment, please don't just copy this code; I suggest you refer to it when you get stuck instead.

This program has a one character needle; you might want to try to improve that.

/*
 *  PatternMatching 
 *  Written by Jason
 */

#include <iostream>
#include <string>
#include <vector>

using namespace std;

const unsigned int matchlen = 5;
string str1("141337545434544543");
string str2("325452134544534513375");

int main (int argc, char * const argv[]) {
    vector<string> matches;
    // Compare each character in the second string
    for (unsigned int i = 0; i < str2.length(); i++) {
        // To each character in the first string
        for (unsigned int j = 0; j < str1.length(); j++) {
            // If two characters match up
            if (str1[j] == str2[i]) {
                // Initialize the resulting string with the first character
                string match(&str1[j], 1);
                unsigned int k = 1;
                if ((j + k) < str1.length() && (i + k) < str2.length()) {
                    // While the next characters of each string are the same
                    while (str1[j+k] == str2[i+k]) {
                        // Append that character to the resulting string
                        match.append(&str1[j+k], 1);
                        k++;
                        if ((j + k) >= str1.length() || (i + k) >= str2.length())
                            break;
                    }
                }
                // If the length of the resulting string is greater than matchlen
                if (match.length() >= matchlen) {
                    // Store it in the matches vector
                    matches.push_back(match);
                }
            }
        }
    }
    
    // Print the results
    for (vector<string>::size_type i = 0; i < matches.size(); i++) {
        cout << matches[i] << endl;
    }
    
    return 0;
}
titaniumdecoy is offline   Reply With Quote