Neat Functions for String Processing

Wanna understand E=mc2, English grammer, or maybe just build a computer? We can help!

Moderator: Moderators

Post Reply
XMEN Ashaman DTM
Inmate
Posts: 2369
Joined: Mon Oct 02, 2000 12:09 am
Location: Silverdale, WA

Neat Functions for String Processing

Post by XMEN Ashaman DTM »

I remembered similar functions from MATLAB. Two functions: one to "explode" a string into chunks, the second to "implode/glue" words to form another string.

I have to say that these functions are handy. Here they are:

Code: Select all

#ifndef STRING_UTILS_H_INCLUDED
#define STRING_UTILS_H_INCLUDED

//
//Header file containing custom string utility functions
//
// List of functions:
//  explode(const string &delim, const string &str)
//      returns an array of substrings parsed from the input string
//
//  implode&#40;const string &glue, const vector<string> &strs&#41;
//      returns a string formed from the vector elements of strs, with glue between each element
//
//

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

using namespace std;

//
//Function Prototypes&#58;
//

vector<string> explode&#40;const string &delim, const string &str&#41;;

string implode&#40;const string &glue, const vector<string> &strs&#41;;


//
//function definitions for string_utils functions
//


vector<string> explode&#40;const string &delim, const string &str&#41;
&#123;
    vector<string> result;
    int delim_length = delim.length&#40;&#41;;  //So that length is calculated once
    int str_length   = str.length&#40;&#41;;    //So that length is calculated once


    if &#40;delim_length==0&#41;
    &#123;
        return&#40;result&#41;;
    &#125;
    else
    &#123;
        int i=0;
        int j=0;
        int k=0;

        while&#40;i < str_length&#41;
        &#123;
            while &#40;i + &#40;j<str_length&#41; && &#40;j<delim_length&#41; && &#40;str&#91;i+j&#93;==delim&#91;j&#93;&#41;&#41;
            &#123;
                j++;
            &#125;
            if &#40;j==delim_length&#41;//found delimiter
            &#123;
                result.push_back&#40;str.substr&#40;k, i-k&#41;&#41;;
                i+=delim_length;
                k=i;
            &#125;
            else
            &#123;
                i++;
            &#125;
        &#125;

        result.push_back&#40;str.substr&#40;k, i-k&#41;&#41;;
        return&#40;result&#41;;
    &#125;
&#125;


string implode&#40;const string &glue, const vector<string> &strs&#41;
&#123;
    string a;
    int i;
    int str_size= strs.size&#40;&#41;;

    for&#40;i=0; i < str_size; ++i&#41;
    &#123;
        a+= strs&#91;i&#93;;
        if &#40;i < &#40;str_size-1&#41;&#41;
        &#123;
            a+= glue;
        &#125;
    &#125;
    return&#40;a&#41;;
&#125;


#endif // STRING_UTILS_H_INCLUDED
Post Reply