c-str cheatsheet – code

printf("%.*s", len, markets) // print c-str without \0
#include <iostream>
#include <string.h>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
void clone(char* orig) {
    char dup[strlen(orig) + 1];//VLA
    strcpy(dup, orig);
    cout << "-- duplicate a string on stack\n" << dup << endl;
    dup[0] = 0;
    cout << "-- now clear its content. New strlen() == \n" << strlen(dup)
            << endl;
}

int main() {
    char a[] = "Four score and seven years ago our fathers brought forth //comment";
    char * const pos5 = strstr(a, "//");
    cout << "-- position of sub-string == " << pos5 << endl;
    *pos5 = '\0';
    cout << "-- rtrim trailing comments -->" << a << "<---\n";
    ////////
    clone(a);
    //////////
    char const b[] = "(extra)";
    char * news = new char[strlen(a) + strlen(b) + 1];
    strcpy(news, a);
    strcat(news, b);
    cout << "-- append and return a heapy\n" << news << endl;
    delete[] news;
    cout << "-- after clearing, strlen ==" << strlen(news) << endl;
    ////////////
    char * pattern = "and";
    int const indexOf = strstr(a, pattern) - a;
    cout << "-- indexOf == " << indexOf << endl;
    //////////
    int const pos = 4;
    news = new char[strlen(a) + strlen(b) + 1];
    strncpy(news, a, pos); //the left half
    strcpy(news + pos, b); //insert
    strcpy(news + strlen(news), a + pos); //the left half
    cout << "-- insert_by_index at position " << pos << endl << news << endl;
    delete[] news;
    //////
    news = new char[strlen(a) + strlen(b) + 1];
    int pos1 = indexOf;
    int pos2 = indexOf + strlen(pattern); //1 past the region
    strncpy(news, a, pos1); //the left half
    strcpy(news + pos1, b);
    strcpy(news + pos1 + strlen(b), a + pos2);//the right half
    cout << "-- replace_by2pos or by substring\n" << news << endl;
    delete[] news;
    //////////
    news = new char[strlen(a) + 1];
    strcpy(news, a);
    pos1 = 1;
    pos2 = 6; //1 past the region
    *(news + pos2) = 0;
    cout << "-- substr_by_pos\n" << news + pos1 << endl;
    /////////
    strcpy(news, a);
    pattern = "ou";
    cout << "-- progressive matching (counting, lastIndexOf..)\n" << endl;
    while (1) {
        news = strstr(news, pattern);
        if (!news)
            break;
        cout << news << endl;
        news += strlen(pattern);
    }
    delete[] news;
    /////////////
    const char* strArray[] = {"aa", "bb"};
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s