Lowest Common Ancestor


//<O(N logN, O(logN)>
#define mx 10010
#define logmx ceil(log(mx))
#define pii pair < int, int >
//#define i64 __int64
#define inf 2147483647

int L[mx], T[mx], P[mx][logmx];
const int root = 1;
bool color[mx];
long long d[mx];
vector < pii > G[mx];
void preprocess(int n){
    int i,j;
    for(i = 1; i <= n; i++)for(j = 0; (1<<j) < n; j++)P[i][j] = -1;
    for(i = 1; i <= n; i++)P[i][0] = T[i];
    for (j = 1; (1<<j) < n; j++)for (i = 1; i <= n; i++)
        if (P[i][j - 1] != -1)
            P[i][j] = P[P[i][j - 1]][j - 1];
}

int getLCA(int p, int q){
    int lg, i;
    if (L[p] < L[q])swap(p,q);
    for (lg = 1; (1<<lg) <= L[p]; lg++);
    lg--;
    for (i = lg; i >= 0; i--)
        if (L[p] - (1 << i) >= L[q])
            p = P[p][i];
    if (p == q)return p;
    for (i = lg; i >= 0; i--)
        if (P[p][i] != -1 && P[p][i] != P[q][i])
            p = P[p][i], q = P[q][i];
    return T[p];
}
Tutorial of Topcoder

RMQ with Segment Tree


#define mx 1000010
#define tmx 2000020

int a[mx];
int t[tmx];
void init(int node, int i, int j){
    if(i==j){
        t[node] = a[i];
        return;
    }
    int mid = (i+j)>> 1;
    init(2*node, i, mid);
    init((2*node)+1, mid+1, j);
    t[node] = max(t[2*node], t[(2*node)+1]);
}
int query(int node, int i, int j, int si, int sj){
    if(i == si && j == sj)return t[node];
    int mid = (i+j)>> 1;
    if(sj <= mid)return query(2*node, i, mid, si, sj);
    else if(si > mid)return query((2*node)+1, mid+1, j, si, sj);
    else{
        int r1 = query(2*node, i, mid, si, mid);
        int r2 = query((2*node)+1, mid+1, j, mid+1, sj);
        return max(r1,r2);
    }
}
void update(int node, int i, int j, int idx, int val){
    if(i == j){
        a[i] = val;
        t[node] = val;
        return;
    }
    int mid = (i+j)>> 1;
    if(idx <= mid) update(2*node, i, mid, idx, val);
    else update ((2*node)+1, mid+1, j, idx, val);
    t[node] = max(t[2*node], t[(2*node)+1]);
}

Binary Indexed Tree


#define i64 long long
i64 BIT[mx];
int n;
//1-D BIT
i64 read(int idx){
    i64 sum = 0;
    while (idx > 0){
        sum += BIT[idx];
        idx -= (idx & -idx);
    }
    return sum;
}

void update(int idx, i64 val){
    while (idx <= m){
        BIT[idx] += val;
        idx += (idx & -idx);
    }
}

//2-D BIT
void update(int x , int y , i64 val){
    int y1;
    while (x <= n){
        y1 = y;
        while (y1 <= n){
            BIT[x][y1] += val;
            y1 += (y1 & -y1); 
        }
        x += (x & -x); 
    }
}

i64 read(int x, int y){
    int y1;
    i64 sum = 0;
    while (x > 0){
        y1 = y;
        while (y1 > 0){
            sum += BIT[x][y1];
            y1 -= (y1 & -y1); 
        }
        x -= (x & -x);
    }
    return sum;
}
Tutorial in Topcoder

Bipartite Matching (Hopcroft-Karp)


//Complexity: O(e√v)
//n: number of nodes in left side n=[1,n]
//m: number of nodes in right side m=[n+1,n+m]
//G: NIL U G1[G[1,n]] U G2[G[n+1,n+m]]

#define mx 100010
#define inf (1<<28)
vector < int > G[mx];
int match[mx], dist[mx];
const int NIL = 0;
bool bfs(int n){
    int i,u,v,sz;
    queue < int > q;
    for(i = 1;i<=n;i++){
        if(match[i]==NIL){
            dist[i] = 0;
            q.push(i);
        }
        else dist[i] = inf;
    }
    dist[NIL] = inf;
    while(!q.empty()){
        u = q.front(); q.pop();
        sz = G[u].size();
        for(i=0;i < sz;i++){
            v = G[u][i];
            if(dist[match[v]]==inf){
                dist[match[v]] = dist[u] + 1;
                q.push(match[v]);
            }
        }
    }
    return (dist[NIL]!=inf);
}

bool dfs(int u){
    int sz,v,i;
    if(u!=NIL){
        sz = G[u].size();
        for(i=0;i < sz;i++){
            v = G[u][i];
            if((dist[match[v]] == dist[u]+1) && dfs(match[v])){
                match[v] = u;
                match[u] = v;
                return true;
            }
        }
        dist[u] = inf;
        return false;
    }
    return true;
}

int Hopcroft_Karp(int n, int m){
    int i,matching;
    for(i=0;i <= (n+m+1);i++)match[i] = NIL;
    matching = 0;
    while(bfs(n)){
        for(i=1;i <= n;i++){
            if(match[i] == NIL && dfs(i))
                matching++;
        }
    }
    return matching;
}

Character Device Driver (for linux)


Little talk.....

This was my 3rd assignment in System programming lab(3rd year undergrad course). The main task of this assignment is to design a character driver which should exist in linux kernel. I make a kernel module which module implements a driver that exposes two character devices to user-space. Lets clarify some topics about this assignment.

Kernel Module

Modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system. For example, one type of module is the device driver, which allows the kernel to access hardware connected to the system. Without modules, we would have to build monolithic kernels and add new functionality directly into the kernel image. Besides having larger kernels, this has the disadvantage of requiring us to rebuild and reboot the kernel every time we want new functionality.

The Driver

Normally a device driver sits between some hardware and the kernel I/O subsystem. Its purpose is to give the kernel a consistent interface to the type of hardware it "drives". This way the kernel can communicate with all hardware of a given type through the same interface, even though the actual hardware differs.

About the driver

sakin_dev The figure to the left illustrates how my driver works. Basically it solves the producer-consumer problem. Here the two processes can be both producers and consumers. This resembles the functionality of a real hardware device driver, where both the hardware and the kernel can produce and consume data.
When a process writes (produces) to character device /dev/sakin-0 the data is stored in bounded buffer 1. If the buffer is full the process has to wait until another process has read from /dev/sakin-1.
When a process reads (consumes) from character device /dev/sakin-0 the data is read from bounded buffer 0. If the buffer is empty the process has to wait until another process has written to /dev/sakin-1.
Writes and reads to and from /dev/sakin-1 are handled in the same way.

Click this link to see my code.

Compiling and inserting the module

Makefile for compiling and creating the module sakin_dev.ko:
obj-m += sakin_dev.o
all:
 make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules
clean:
 make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean
script for loading the module sakin_dev.ko and creating the device file:
#file name sakin_load
#!/bin/sh
module_name="sakin_dev"
device_prefix="sakin-"
mode="664"
group="root"

# invoke insmod
# use a pathname, as newer modutils don't look in . by default
insmod ./${module_name}.ko

# retrieve major number
major=$(awk "\$2==\"$module_name\" {print \$1}" /proc/devices)

# Remove stale nodes and replace them, then give gid and perms
# Usually the script is shorter, it's scull that has several devices in it.

rm -f /dev/${device_prefix}[0-1]
mknod /dev/${device_prefix}0 c $major 0
mknod /dev/${device_prefix}1 c $major 1
chgrp $group /dev/${device_prefix}[0-1]
chmod $mode  /dev/${device_prefix}[0-1]
script for unloading the module sakin_dev.o and removing the device file:
#file name sakin_unload
#!/bin/sh
module_name="sakin_dev"
device_prefix="sakin-"

# invoke rmmod with all arguments we got
rmmod ${module_name}

# Remove stale nodes
rm -f /dev/${device_prefix}[0-1]
Now compile the module by running make. If the compilation succeeds there will now be a file called sakin_dev.ko which is the module. Create the necessary devices and insert the module by executing
./sakin_load
To remove the module and to delete the devices execute:
./sakin_unload

Functions and Macros:

int sakin_init_module( void ): init_function, Called when module is loaded into the kernel.
void sakin_cleanup_module( void ): cleanup_function, Called when module is unloaded from the kernel.
module_init(init_function): Macros that designate a modules initialization, defined in <linux/types.h>.
module_exit(cleanup_function): Macros that designate a modules cleanup functions, defined in <linux/types.h>.

static int sakin_open( struct inode*, struct file* ): Called when a process tries to open the device file.
static int sakin_release( struct inode*, struct file* ): Called when a process closes the device file.

static ssize_t sakin_read( struct file*, char*, size_t, loff_t* ): Called when a process, which already opened the sakin_dev file, attempts to read from it.
static int sakin_getwritespace(struct sakin_dev *dev, struct file *filp, const int c_minor): Wait for space for writing. Caller must hold device semaphore. On error the semaphore will be released before returning.
static int spacefree(struct sakin_dev *dev, const int c_minor): Return how much space is free.
static ssize_t sakin_write( struct file*, const char*, size_t, loff_t* ): Called when a process, which already opened the sakin_dev file, attempts to write to it.

dev_t MKDEV(unsigned int major, unsigned int minor): Macro that builds a dev_t data item from the major and minor numbers. Declared in <linux/types.h>.
int register_chrdev_region(dev_t first, unsigned int count, char *name): Allocating the device number, which is declared in <linux/fs.h>
void unregister_chrdev_region(dev_t first, unsigned int count): Freeing the device number, which is declared in <linux/fs.h>
container_of(pointer, type, field): A convenience macro that may be used to obtain a pointer to a structure from a pointer to some other structure contained within it.
void *kmalloc(size_t size, int flags): For allcating memory, which is declared in <linux/slab.h>
void kfree(void *ptr); For freeing memory, which is declared in <linux/slab.h>
static void sakin_setup_cdev(struct sakin_dev *dev, int index): Local function to setup the char device.
void cdev_init(struct cdev *cdev, struct file_operations *fops): Initializing and setting up the char device. Declared in <linux/cdev.h>
int cdev_add(struct cdev *dev, dev_t num, unsigned int count): Tell the kernel about the char device. Declared in <linux/cdev.h>
void cdev_del(struct cdev *dev): To remove a char device from the system. Declared in <linux/cdev.h>
unsigned int iminor(struct inode *inode),
unsigned int imajor(struct inode *inode):
used to obtain the major and minor number from an inode.
unsigned long copy_from_user (void *to, const void *from, unsigned long count),
unsigned long copy_to_user (void *to, const void *from, unsigned long count):
Copy data between user space and kernel space. Declared in <asm/uaccess.h>
void schedule(void): Selects a runnable process from the run queue. The chosen process can be current or a different one.
bool signal_pending(current): Tells whether current were awakened by a signal.
GFP_USER & GFP_KERNEL:
Flags that control how memory allocations are performed, from the least restrictive to the most. The GFP_USER and GFP_KERNEL priorities allow the current process to be put to sleep to satisfy the request.

Semaphore related functions defined in <asm/semaphore.h>
void sema_init(struct semaphore *sem, int val): Semaphore initialization.
void down(struct semaphore *sem): down puts the calling process into an uninterruptible sleep if need be.
int down_interruptible(struct semaphore *sem): down_interruptible, instead, can be interrupted by a signal.
int down_trylock(struct semaphore *sem): down_trylock does not sleep; instead, it returns immediately if the semaphore is unavailable.
void up(struct semaphore *sem): Code that locks a semaphore must eventually unlock it with up.

Sleep related functions defined in <linux/wait.h>
void init_waitqueue_head(wait_queue_head_t *queue);
DECLARE_WAIT_QUEUE_HEAD(queue):

The defined type for Linux wait queues. A wait_queue_head_t must be explicitly initialized with either init_waitqueue_head at runtime or DECLARE_WAIT_QUEUE_HEAD at compile time.
void wait_event(wait_queue_head_t q, int condition); //uninterruptible wait
int wait_event_interruptible(wait_queue_head_t q, int condition); //interruptible wait
int wait_event_timeout(wait_queue_head_t q, int condition, int time); //uninterruptible timeout wait
int wait_event_interruptible_timeout(wait_queue_head_t q, int condition, int time): //interruptible timeout wait
Cause the process to sleep on the given queue until the given condition evaluates to a true value.
void prepare_to_wait(wait_queue_head_t *queue, wait_queue_t *wait, int state),
void finish_wait(wait_queue_head_t *queue, wait_queue_t *wait):
Helper functions that can be used to code a manual sleep.
void wake_up(struct wait_queue **q); //uninterruptible
void wake_up_interruptible(struct wait_queue **q); //interruptible
void wake_up_nr(struct wait_queue **q, int nr);
void wake_up_interruptible_nr(struct wait_queue **q, int nr);
void wake_up_all(struct wait_queue **q);
void wake_up_interruptible_all(struct wait_queue **q):

Wake processes that are sleeping on the queue q. The _interruptible form wakes only interruptible processes. Normally, only one exclusive waiter is awakened, but that behavior can be changed with the _nr or _all forms.

Externel References:

The Linux Kernel Module Programming Guide
Linux Device Driver (Ch:2,3,5,6)

ls (my own implementation)


Little talk about 'ls' (since I have very small knowledge about it):
ls - list directory contents.

The 'ls' program lists information about files (of any type, including directories). Options and file arguments can be intermixed arbitrarily, as usual.
Know details about 'ls' in linux man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?ls

Little talk about coding:
Probably I wouldn't write this code in my entire life unless I got it as my lab assignment :D. It was my 2nd year System Programming lab assignment. However, at first, it seemed very disgusting and painful task to me. But after started coding, it was fun to write the code.
I tried to make my 'ls' as like as linux's 'ls' implementation. Since I was not very familiar with linux, before doing this assignment, firstly I checked out all the options provided by the 'ls' process. Actually, I had to learn about all the functionalities it has :D.

Implementation:
I used c++ as the programming language. I have the name of a directory or file in dirent->d_name & and by using lstat() function, I retrieved all the information about a file or directory.
  • I saved each file or directory name and statistics in a vector.
  • Applying printing format given by the OPTIONS.
  • Print the corresponding information.
A closer look at lstat() in linux man page: http://linux.die.net/man/2/lstat
Here is my coding.........


/*
 * Course: CSE-326 System Programming Lab
 * Assignment No: 02
 * Assignment Name: ls — list directory contents
 * SYNOPSIS: ls [-AacdFfhiklnoqRrSstuw1] [file . . .]
 * Author: Sayef Azad Sakin
 * Roll: 1563
 * Language: c++
 */
 
#ifndef BLOCKSIZE
#define BLOCKSIZE 512
#endif
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <climits>
#include <algorithm>
using namespace std;

#define eps 1e-11
#define mx 1000

struct files{
 string name, full_path;
 struct stat st;
 files(string ps, string s, struct stat &ss){
  full_path = ps;
  name = s;
  st = ss;
 }
};

vector < files > name, dir_name[10], dir_path, rfile, rdir;
vector < files >:: iterator it;
bool flag[30];
int tot_dir;
char chk[] = {'A','a','c','d','F','f','h','i','k','l','n','o','q','R','r','S','s','t','u','w','1'};

bool comp(const files &a, const files &b){
 if(flag[15]){//-S
  if(a.st.st_size == b.st.st_size){
   if(flag[17]){//-t
    if(a.st.st_mtime == b.st.st_mtime)return (a.name<b.name);
    return (a.st.st_mtime < b.st.st_mtime);
   }
   return (a.name<b.name);
  }
  return (a.st.st_size > b.st.st_size);
 }
 if(flag[17]){//-t
  if(a.st.st_mtime == b.st.st_mtime)return (a.name<b.name);
  return (a.st.st_mtime < b.st.st_mtime);
 }
 if(flag[2]){//-c
  if(a.st.st_ctime == b.st.st_ctime)return (a.name<b.name);
  return (a.st.st_ctime < b.st.st_ctime);
 }
 if(flag[18]){//-u
  if(a.st.st_atime == b.st.st_atime)return (a.name<b.name);
  return (a.st.st_atime < b.st.st_atime);
 }
 return (a.name<b.name);
}

int getfile(files fdes);
int chkflag(char *str);
void print(const files fdes);

int main(int argc, char **argv){
 int argpos, i, sz;
 bool ok;
 char path[mx], cwd[mx];
 dirent *dirp;
 DIR *dp;
 struct stat f_stat;
 //initialize();
 //parsing starts here
 ok = 0;
 for(argpos = 1; argpos < argc; argpos++){
  if(argv[argpos][0]=='-'){
   if(chkflag(argv[argpos])==-1){puts("argument error");return 2;}
  }
  else{
   if (lstat(argv[argpos], &f_stat) == -1){puts("statistics error");return -1;}
   if(S_ISREG(f_stat.st_mode) || !strcmp(argv[argpos],".") || !strcmp(argv[argpos],".."))rfile.push_back(files(argv[argpos],argv[argpos],f_stat));
   else if(S_ISDIR(f_stat.st_mode))rdir.push_back(files(argv[argpos],argv[argpos],f_stat));
   ok = 1;
  }
 }
 if(!ok){
  if( !getcwd(cwd,mx) ) return 1;
  
  if( !(dp = opendir(cwd)) ){puts("error on opening current directory");return 3;}
  while( (dirp = readdir(dp)) ){
   strcpy(path,".");
   strcat(path,"/");
   strcat(path,dirp->d_name);
   if (lstat(path, &f_stat) == -1){puts("statistics error");return -1;}
   if(S_ISREG(f_stat.st_mode) || !strcmp(dirp->d_name,".") || !strcmp(dirp->d_name,".."))rfile.push_back(files(path,dirp->d_name,f_stat));
   else if(S_ISDIR(f_stat.st_mode))rdir.push_back(files(path,dirp->d_name,f_stat));
  }
  if( closedir(dp) < 0 ){puts("can't close directory");return -1;}
 }
 //parsing ends here

 //sorting starts here
 sort(rfile.begin(),rfile.end(),comp);
 sort(rdir.begin(),rdir.end(),comp);
 if(flag[14]){//-r
  reverse(rfile.begin(),rfile.end());
  reverse(rdir.begin(),rdir.end());
 }
 //sorting ends here
 
 sz = rfile.size();
 for(i=0;i<sz;i++)
  print(rfile[i]);
 if(!ok || flag[3]){//-d
  sz = rdir.size();
  for(i=0;i<sz;i++)
   print(rdir[i]);
  return 0;
 }
 puts("");
 sz = rdir.size();
 
 if(ok || flag[13]){//-R
  for(i=0;i<sz;i++){
   cout << rdir[i].name << ":(under this direcotry) " << endl;
   if(getfile(rdir[i])==-1)return 5;
  }
 }
 return 0;
}

int getfile(files fdes){
 dirent *dirp;
 DIR *dp;
 vector < files > tfile, tdir;
 struct stat file_stat;
 char path[mx], tpath[mx];
 int sz, i;
 strcpy(path,fdes.full_path.c_str());
 if( !(dp = opendir(path)) ){puts("error on opening directory");return -1;}
 while( (dirp = readdir(dp)) ){
  strcpy(tpath,path);
  sz = strlen(tpath);
  if(tpath[sz-1]!='/'){
   tpath[sz] = '/'; tpath[sz+1] = 0;
  }
  strcat(tpath,dirp->d_name);
  //printf("%s\n",tpath);
  if (lstat(tpath, &file_stat) == -1){puts("statistics error");return -1;}
  if(S_ISREG(file_stat.st_mode) || !strcmp(dirp->d_name,".") || !strcmp(dirp->d_name,".."))tfile.push_back(files(tpath,dirp->d_name,file_stat));
  else if(S_ISDIR(file_stat.st_mode))tdir.push_back(files(tpath,dirp->d_name,file_stat));
 }
 if( closedir(dp) < 0 ){puts("can't close directory");return -1;}
 
 //sorting starts here
 sort(tfile.begin(),tfile.end(),comp);
 sort(tdir.begin(),tdir.end(),comp);
 if(flag[14]){//-r
  reverse(tfile.begin(),tfile.end());
  reverse(tdir.begin(),tdir.end());
 }
 //sorting ends here
 
 sz = tfile.size();
 for(i=0;i<sz;i++)
  print(tfile[i]);
 sz = tdir.size();
 for(i=0;i<sz;i++)
  print(tdir[i]);
 puts("");
 if(flag[3])return 0;//-d
 if(flag[13]){
  sz = tdir.size();
  for(i=0;i<sz;i++){
   cout << tdir[i].name << ":(under this direcotry) " << endl;
   if(getfile(tdir[i])==-1)return -1;
  }
 }
 return 0;
}

int chkflag(char *str){
 bool ok;
 int i,j;
 for(i = 1;str[i]; i++){
  if(str[i]=='R' && flag[3])continue;
  ok = 0;
  for(j=0;j<21;j++){
   if(chk[j]=='h' && str[i]=='k')flag[j] = 0;
   else if(chk[j]=='k' && str[i]=='h')flag[j] = 0;
   else if(chk[j]=='1' && str[i]=='l')flag[j] = 0;
   else if(chk[j]=='l' && str[i]=='1')flag[j] = 0;
   else if(chk[j]=='c' && str[i]=='u')flag[j] = 0;
   else if(chk[j]=='u' && str[i]=='c')flag[j] = 0;
   else if(chk[j]=='q' && str[i]=='w')flag[j] = 0;
   else if(chk[j]=='w' && str[i]=='q')flag[j] = 0;
   else if(chk[j]=='R' && str[i]=='d')flag[j] = 0;
   
   if(chk[j]==str[i]){ok=1;break;}
  }
  if(ok)flag[j] = 1;
  else return -1;
 }
 return 0;
}

void print(const files fdes){
 double sz;
 struct tm *ts;
 char ptime[20];
 struct passwd *ps;
 struct group *gr;
 sz = fdes.st.st_size;
 if(!flag[1] && (fdes.name == "." || fdes.name == ".."))return;
 if(flag[7])printf("%u ",fdes.st.st_ino);//-i
 if(flag[16]){//-s
  sz = fdes.st.st_blocks*512;
  if(!flag[6] && !flag[8]){
   sz /=1024;
   printf("%5.0lf ",ceil(sz));
  }
 }
 if(flag[6] && flag[16]){//-h
  if(sz>1073741824 || fabs(sz-1073741824)<eps){
   sz /= 1073741824;
   printf("%.1lfG ",sz+eps);
  }
  else if(sz>1048576 || fabs(sz-1048576)<eps){
   sz /= 1048576;
   printf("%.1lfM ",sz+eps);
  }
  else if(sz>1024 || fabs(sz-1024)<eps){
   sz /= 1024;
   printf("%.1lfK ",sz+eps);
  }
  else printf("%.0lf ",sz);
 }
 if(flag[8] && flag[16]){//-k
  sz /= 1024;
  printf("%5.0lf ",ceil(sz));
 }
 if(flag[9] || flag[10] || flag[13]){//-l & -n
  //file mode
  //entry type
  if(S_ISBLK(fdes.st.st_mode))printf("b");
  else if(S_ISCHR(fdes.st.st_mode))printf("c");
  else if(S_ISDIR(fdes.st.st_mode))printf("d");
  else if(S_ISLNK(fdes.st.st_mode))printf("l");
  else if(S_ISSOCK(fdes.st.st_mode))printf("s");
  else if(S_ISFIFO(fdes.st.st_mode))printf("p");
  else if(S_ISREG(fdes.st.st_mode))printf("-");
  //owner permission
  printf((fdes.st.st_mode & S_IRUSR)?"r":"-");
  printf((fdes.st.st_mode & S_IWUSR)?"w":"-");
  if((S_ISREG(fdes.st.st_mode) || S_ISDIR(fdes.st.st_mode)) && fdes.st.st_mode & 0111)
   printf((fdes.st.st_mode & S_ISUID)?"s":"x");
  else
   printf((fdes.st.st_mode & S_ISUID)?"S":"-");
  //group permission
  printf((fdes.st.st_mode & S_IRGRP)?"r":"-");
  printf((fdes.st.st_mode & S_IWGRP)?"w":"-");
  if((S_ISREG(fdes.st.st_mode) || S_ISDIR(fdes.st.st_mode)) && fdes.st.st_mode & 0111)
   printf((fdes.st.st_mode & S_ISGID)?"s":"x");
  else
   printf((fdes.st.st_mode & S_ISGID)?"S":"-");
  //other permission
  printf((fdes.st.st_mode & S_IROTH)?"r":"-");
  printf((fdes.st.st_mode & S_IWOTH)?"w":"-");
  if((S_ISREG(fdes.st.st_mode) || S_ISDIR(fdes.st.st_mode)) && fdes.st.st_mode & 0111)
   printf((fdes.st.st_mode & S_ISVTX)?"t":"-");
  else
   printf((fdes.st.st_mode & S_ISVTX)?"T":"-");
  
  //number of links
  printf(" %u",fdes.st.st_nlink);
  
  //user name & group name
  if(flag[10])printf(" %5u%5u",fdes.st.st_uid,fdes.st.st_gid);
  else{
   ps = getpwuid(fdes.st.st_uid);
   printf(" %s ",ps->pw_name);
   if(!flag[13]){
    gr = getgrgid(fdes.st.st_gid);
    printf(" %s",gr->gr_name);
   }
  }
  
  //no of bytes
  sz = fdes.st.st_size;
  if(flag[6]){//-h
   if(sz>1073741824 || fabs(sz-1073741824)<eps){
    sz /= 1073741824;
    printf("%10.1lfG ",sz+eps);
   }
   else if(sz>1048576 || fabs(sz-1048576)<eps){
    sz /= 1048576;
    printf("%10.1lfM ",sz+eps);
   }
   else if(sz>1024 || fabs(sz-1024)<eps){
    sz /= 1024;
    printf("%10.1lfK ",sz+eps);
   }
   else printf("%10.0lf ",sz);
  }
  else if(flag[8]){//-k
   sz /= 1024;
   printf("%10.0lf ",ceil(sz));
  }
  else printf("%10.0lf ",sz);
  
  //year-month-day hh:mm
  ts = localtime(&fdes.st.st_mtime);
  strftime(ptime, sizeof(ptime), "%Y-%m-%d %H:%M", ts);
  printf("%s ", ptime);
 }
 
 cout << fdes.name;
 if(flag[4]){//-F
  if(S_ISDIR(fdes.st.st_mode))printf("/");
  else if(S_ISREG(fdes.st.st_mode) && fdes.st.st_mode & 0111)printf("*");
  else if(S_ISLNK(fdes.st.st_mode))printf("@");
  //else if(S_IFWHT(fdes.st.st_mode))printf("@");
  else if(S_ISSOCK(fdes.st.st_mode))printf("=");
  else if(S_ISFIFO(fdes.st.st_mode))printf("|");
 }
 puts("");
}

MAKEFILE (at a glance)


Sample code
 
project1: data.o main.o io.o
        cc data.o main.o io.o -o project1
data.o: data.c data.h
        cc -c data.c
main.o: data.h io.h main.c
        cc -c main.c
io.o: io.h io.c
        cc -c io.c #this is a comment

Syntex
target : source file(s)
command (must be preceded by a tab)

#command to use user defined makefile name
make -f mymakefile

Macros in make
The make program allows to use macros, which are similar to variables, to store names of files. The format is as follows:
OBJECTS = data.o io.o main.o
Whenever you want to have make expand these macros out when it runs, type the following corresponding string $(OBJECTS).

Here is sample Makefile again, using a macro.
OBJECTS = data.o main.o io.o
project1: $(OBJECTS)
        cc $(OBJECTS) -o project1
data.o: data.c data.h
        cc -c data.c
main.o: data.h io.h main.c
        cc -c main.c
io.o: io.h io.c
        cc -c io.c
You can also specify a macro's value when running make, as follows:
make 'OBJECTS=data.o newio.o main.o' project1
This overrides the value of OBJECTS in the Makefile

Special Macros
CC:
Contains the current C compiler. Defaults to cc.
CFLAGS:
Special options which are added to the built-in C rule.
$@:
Full name of the current target.
$?:
A list of files for current dependency which are out-of-date.
$<:
The source file of the current (single) dependency.

External Links:
http://www.eng.hawaii.edu/Tutor/Make/1.html
http://www.opussoftware.com/tutorial/TutMakefile.htm

Windows 7 Command Prompt Commands


Append:
It can be used by programs to open files in another directory as if they were located in the current directory.
Arp:
It is used to display or change entries in the ARP cache..
Assoc:
The assoc command is used to display or change the file type associated with a particular file extension..
At:
The at command is used to schedule commands and other programs to run at a specific date and time..
Attrib:
The attrib command is used to change the attributes of a single file or a directory..
Auditpol:
The auditpol command is used to display or change audit policies..
Bcdedit:
The bcdedit command is used to view or make changes to Boot Configuration Data..
Bitsadmin:
The bitsadmin command is used to create, manage, and monitor download and upload jobs..
Bootcfg:
The bootcfg command is used to build, modify, or view the contents of the boot.ini file, a hidden file that is used to identify in what folder, on which partition, and on which hard drive Windows is located..
Break:
The break command sets or clears extended CTRL+C checking on DOS systems.
Cacls:
The cacls command is used to display or change access control lists of files.
Call:
The call command is used to run a script or batch program from within another script or batch program..
Certreq:
The certreq command is used to perform various certification authority (CA) certificate functions..
Certutil:
The certutil command is used to dump and display certification authority (CA) configuration information in addition to other CA functions..
Change:
The change command changes various terminal server settings like install modes, COM port mappings, and logons..
Chcp:
The chcp command displays or configures the active code page number..
Chdir:
The chdir command is used to display the drive letter and folder that you are currently in. Chdir can also be used to change the drive and/or directory that you want to work in..
Chglogon:
The chglogon command enables, disables, or drains terminal server session logins..
Chgport:
The chgport command can be used to display or change COM port mappings for DOS compatibility..
Chgusr:
The chgusr command is used to change the install mode for the terminal server.
Chkdsk:
The chkdsk command, often referred to as check disk, is used to identify and correct certain hard drive errors.
Chkntfs:
The chkntfs command is used to configure or display the checking of the disk drive during the Windows boot process..
Choice:
The choice command is used within a script or batch program to provide a list of choices and return of the value of that choice to the program..
Cipher:
The cipher command shows or changes the encryption status of files and folders on NTFS partitions..
Clip:
The clip command is used to redirect the output from any command to the clipboard in Windows..
Cls:
The cls command clears the screen of all previously entered commands and other text..
Cmd:
The cmd command starts a new instance of the command interpreter..
Cmdkey:
The cmdkey command is used to show, create, and remove stored user names and passwords..
Cmstp:
The cmstp command installs or uninstalls a Connection Manager service profile..
Color:
The color command is used to change the colors of the text and background within the Command Prompt window.
Comp:
The comp command is used to compare the contents of two files or sets of files.
Compact:
The compact command is used to show or change the compression state of files and directories on NTFS partitions..
Convert:
The convert command is used to convert FAT or FAT32 formatted volumes to the NTFS format..
Copy:
The copy command does simply that - it copies one or more files from one location to another..
Date:
The date command is used to show or change the current date..
Debug:
The debug command starts Debug, a command line application used to test and edit programs..
Defrag:
The defrag command is used to defragment a drive you specify. The defrag command is the command line version of Microsoft's Disk Defragmenter..
Del:
The del command is used to delete one or more files. The del command is the same as the erase command..
Dir:
The dir command is used to display a list of files and folders contained inside the folder that you are currently working in. The dir command also displays other important information like the hard drive's serial number, the total number of files listed, their combined size, the total amount of free space left on the drive, and more..
Diskcomp:
The diskcomp command is used to compare the contents of two floppy disks.
Diskcopy:
The diskcopy command is used to copy the entire contents of one floppy disk to another.
Diskpart:
The diskpart command is used to create, manage, and delete hard drive partitions..
Diskraid:
The diskraid command starts the DiskRAID tool which is used to manage and configure RAID arrays..
Dism:
The dism command starts the Deployment Image Servicing and Management tool (DISM). The DISM tool is used to manage features in Windows images..
Dispdiag:
The dispdiag command is used to output a log of information about the display system..
Doskey:
The doskey command is used to edit command lines, create macros, and recall previously entered commands..
Driverquery:
The driverquery command is used to show a list of all installed drivers..
Echo:
The echo command is used to show messages, most commonly from within script or batch files. The echo command can also be used to turn the echoing feature on or off..
Edit:
The edit command starts the MS-DOS Editor tool which is used to create and modify text files..
Edlin:
The edlin command starts the Edlin tool which is used to create and modify text files from the command line.
Endlocal:
The endlocal command is used to end the localization of environment changes inside a batch or script file.
Erase:
The erase command is used to delete one or more files. The erase command is the same as the del command..
Eventcreate:
The eventcreate command is used to create a custom event in an event log..
Exe2Bin:
The exe2bin command is used to convert a file of the EXE file type (executable file) to a binary file..
Exit:
The exit command is used to end the Command Prompt session that you're currently working in..
Expand:
The expand command is used to extract a single file or a group of files from a compressed file..
Fastopen:
The fastopen command is used to add a program's hard drive location to a special list stored in memory, potentially improving the program's launch time by removing the need for MS-DOS to locate the application on the drive..
Fc:
The fc command is used to compare two individual or sets of files and then show the differences between them..
Find:
The find command is used to search for a specified text string in one or more files..
Findstr:
The findstr command is used to find text string patterns in one or more files.
Finger:
The finger command is used to return information about one or more users on a remote computer that's running the Finger service.
For:
The for command is used to run a specified command for each file in a set of files. The for command is most often used within a batch or script file..
Forfiles:
The forfiles command selects one or more files to execute a specified command on. The forfiles command is most often used within a batch or script file..
Format:
The format command is used to format a drive in the file system that you specify..
Fsutil:
The fsutil command is used to perform various FAT and NTFS file system tasks like managing reparse points and sparse files, dismounting a volume, and extending a volume..
Ftp:
The ftp command can used to transfer files to and from another computer. The remote computer must be operating as an FTP server..
Ftype:
The ftype command is used to define a default program to open a specified file type..
Getmac:
The getmac command is used to display the media access control (MAC) address of all the network controllers on a system..
Goto:
The goto command is used in a batch or script file to direct the command process to a labeled line in the script..
Gpresult:
The gpresult command is used to display Group Policy settings.
Gpupdate:
The gpupdate command is used to update Group Policy settings.
Graftabl:
The graftabl command is used to enable the ability of Windows to display an extended character set in graphics mode.
Graphics:
The graphics command is used to load a program that can print graphics..
Help:
The help command provides more detailed information on any of the other Command Prompt commands..
Hostname:
The hostname command displays the name of the current host..
Icacls:
The icacls command is used to display or change access control lists of files. The icacls command is an updated version of the cacls command..
If:
The if command is used to perform conditional functions in a batch file..
Ipconfig:
The ipconfig command is used to display detailed IP information for each network adapter utilizing TCP/IP. The ipconfig command can also be used to release and renew IP addresses on systems configured to receive them via a DHCP server..
Irftp:
The irftp command is used to transmit files over an infrared link..
Iscsicli:
The iscsicli command starts the Microsoft iSCSI Initiator, used to manage iSCSI.
Label:
The label command is used to manage the volume label of a disk.v Loadfix:
The loadfix command is used to load the specified program in the first 64K of memory and then runs the program..
Lodctr:
The lodctr command is used to update registry values related to performance counters..
Logman:
The logman command is used to create and manage Event Trace Session and Performance logs. The logman command also supports many functions of Performance Monitor..
Logoff:
The logoff command is used to terminate a session..
Mem:
The mem command shows information about used and free memory areas and programs that are currently loaded into memory in the MS-DOS subsystem..
Mkdir (Md) :
The mkdir command is used to create a new folder..
Mklink:
The mklink command is used to create a symbolic link..
Mmc:
The mmc command can be used to open Microsoft Management Console in author mode or to a specific snap-in console, all from the Command Prompt..
Mode:
The mode command is used to configure system devices, most often COM and LPT ports.
More:
The more command is used to display the information contained in a text file. The more command can also be used to paginate the results of any other Command Prompt command.
Mountvol:
The mountvol command is used to display, create, or remove volume mount points..
Move:
The move command is used to move one or files from one folder to another. The move command is also used to rename directories..
Msg:
The msg command is used to send a message to a user..
Msiexec:
The msiexec command is used to start Windows Installer, a tool used to install and configure software.
Mstsc:
The mstsc command starts the Remote Desktop Connection tool from the Command Prompt.
Muiunattend:
The muiunattend command starts the Multilanguage User Interface unattended setup process..
Nbtstat:
The nbtstat command is used to show TCP/IP information and other statistical information about a remote computer..
Net:
The net command is used to display, configure, and correct a wide variety of network settings..
Netcfg:
The netcfg command is used to install the Windows Preinstallation Environment (WinPE), a lightweight version of Windows used to deploy workstations..
Netstat:
The netstat command is most commonly used to display all open network connections and listening ports..
Nlsfunc:
The nlsfunc command is used to load information specific to a particular country or region..
Nltest:
The nltest command is used to test secure channels between Windows computers in a domain and between domain controllers that are trusting other domains..
Nslookup:
The nslookup is most commonly used to display the hostname of an entered IP address. The nslookup command queries your configured DNS server to discover the IP address..
Ocsetup:
The ocsetup command starts the Windows Optional Component Setup tool, used to install additional Windows features.
Openfiles:
The openfiles command is used to display and disconnect open files and folders on a system.
Path:
The path command is used to display or set a specific path available to executable files..
Pathping:
The pathping command functions much like the tracert command but will also report information about network latency and loss at each hop..
Pause:
The pause command is used within a batch or script file to pause the processing of the file. When the pause command is used, a Press any key to continue... message displays in the command window..
Ping:
The ping command sends an Internet Control Message Protocol (ICMP) Echo Request message to a specified remote computer to verify IP-level connectivity..
Pkgmgr:
The pkgmgr command is used to start the Windows Package Manager from the Command Prompt. Package Manager installs, uninstalls, configures, and updates features and packages for Windows..
Pnpunattend:
The pnpunattend command is used to automate the installation of hardware device drivers..
Pnputil:
The pnputil command is used to start the Microsoft PnP Utility, a tool used to install a Plug and Play device from the command line..
Popd:
The popd command is used to change the current directory to the one most recently stored by the pushd command. The popd command is most often utilized from within a batch or script file..
Print:
The print command is used to print a specified text file to a specified printing device.
Prompt:
The prompt command is used to customize the appearance of the prompt text in Command Prompt.
Pushd:
The pushd command is used to store a directory for use, most commonly from within a batch or script program..
Qappsrv:
The qappsrv command is used to display all Remote Desktop Session Host servers available on the network..
Qprocess:
The qprocess command is used to display information about running processes..
Query:
The query command is used to display the status of a specified service..
Quser:
The quser command is used to display information about users currently logged on to the system..
Qwinsta:
The qwinsta command is used to display information about open Remote Desktop Sessions..
Rasdial:
The rasdial command is used to start or end a network connection for a Microsoft client..
Recover:
The recover command is used to recover readable data from a bad or defective disk..
Reg:
The reg command is used to manage the Windows Registry from the command line. The reg command can perform common registry functions like adding registry keys, exporting the registry, etc.
Regsvr32:
The regsvr32 command is used to register a DLL file as a command component in the Windows Registry.
Relog:
The relog command is used to create new performance logs from data in existing performance logs..
Rem:
The rem command is used to record comments or remarks in a batch or script file..
Rename (Ren):
The rename command is used to change the name of the individual file that you specify..
Replace:
The replace command is used to replace one or more files with one or more other files..
Reset Session (Rwinsta):
The reset session command is used to reset the session subsystem software and hardware to known initial values..
Rmdir (Rd):
The rmdir command is used to delete an existing and completely empty folder..
Robocopy:
The robocopy command is used to copy files and directories from one location to another. The robocopy command is superior to the more simple copy command because robocopy supports many more options. This command is also called Robust File Copy..
Route:
The route command is used to manipulate network routing tables..
Rpcping:
The rpcping command is used to ping a server using RPC.
Runas:
The runas command is used to execute a program using another user's credentials.
Sc:
The sc command is used to configure information about services. The sc command communicates with the Service Control Manager..
Schtasks:
The schtasks command is used to schedule specified programs or commands to run a certain times. The schtasks command can be used to create, delete, query, change, run, and end scheduled tasks..
Secedit:
The secedit command is used to configure and analyze system security by comparing the current security configuration to a template..
Set:
The set command is used to enable or disable certain options in Command Prompt..
Setlocal:
The setlocal command is used to start the localization of environment changes inside a batch or script file..
Setver:
The setver command is used to set the MS-DOS version number that MS-DOS reports to a program..
Setx:
The setx command is used to create or change environment variables in the user environment or the system environment..
Sfc:
The sfc command is used to verify and replace important Windows system files. The sfc command is also referred to as System File Checker and Windows Resource Checker..
Shadow:
The shadow command Is used to monitor another Remote Desktop Services session.
Share:
The share command is used to install file locking and file sharing functions in MS-DOS.
Shift:
The shift command is used to change the position of replaceable parameters in a batch or script file..
Shutdown:
The shutdown command can be used to shut down, restart, or log off the current system or a remote computer..
Sort:
The sort command is used to read data from a specified input, sort that data, and return the results of that sort to the Command Prompt screen, a file, or another output device..
Start:
The start command is used to open a new command line window to run a specified program or command. The start command can also be used to start an application without creating a new window..
Subst:
The subst command is used to associate a local path with a drive letter. The subst command is a lot like the net use command except a local path is used instead of a shared network path..
Sxstrace:
The sxstrace command is used to start the WinSxs Tracing Utility, a programming diagnostic tool..
Systeminfo:
The systeminfo command is used to display basic Windows configuration information for the local or a remote computer..
Takeown:
The takedown command is used to regain access to a file that that an administrator was denied access to when reassigning ownership of the file..
Taskkill:
The taskkill command is used to terminate a running task. The taskkill command is the command line equivalent of ending a process in Task Manager in Windows.
Tasklist:
"Displays a list of applications, services, and the Process ID (PID) currently running on either a local or a remote computer.
Tcmsetup:
The tcmsetup command is used to setup or disable the Telephony Application Programming Interface (TAPI) client..
Time:
The time command is used to show or change the current time..
Timeout:
The timeout command is typically used in a batch or script file to provide a specified timeout value during a procedure. The timeout command can also be used to ignore keypresses..
Title:
The title command is used to set the Command Prompt window title..
Tracerpt:
The tracerpt command is used to process event trace logs or real-time data from instrumented event trace providers..
Tracert:
The tracert command sends Internet Control Message Protocol (ICMP) Echo Request messages to a specified remote computer with increasing Time to Live (TTL) field values and displays the IP address and hostname, if available, of the router interfaces between the source and destination..
Tree:
The tree command is used to graphically display the folder structure of a specified drive or path..
Tsdiscon:
The tsdiscon command is used to disconnect a Remote Desktop session..
Tskill:
The tskill command is used to end the specified process.
Type:
The type command is used to display the information contained in a text file.
Typeperf:
The typerperf command displays performance data in the Command Prompt window or writes the data to specified log file..
Tzutil:
The tzutil command is used to display or configure the current system's time zone. The tzutil command can also be used to enable or disable automatic Daylight Saving Time adjustments..
Unlodctr:
The unlodctr command removes Explain text and Performance counter names for a service or device driver from the Windows Registry..
Ver:
The ver command is used to display the current Windows version..
Verify:
The verify command is used to enable or disable the ability of Command Prompt to verify that files are written correctly to a disk..
Vol:
The vol command shows the volume label and serial number of a specified disk, assuming this information exists..
Vssadmin:
The vssadmin command starts the Volume Shadow Copy Service administrative command line tool which displays current volume shadow copy backups and all installed shadow copy writers and providers..
W32Tm:
The w32tm command is used to diagnose issues with Windows Time..
Waitfor:
The waitform command is used to send or wait for a signal on a system.
Wbadmin:
The wbadmin command is used start and stop backup jobs, display details about a previous backup, list the items within a backup, and report on the status of a currently running backup.
Wevtutil:
The wevtutil command starts the Windows Events Command Line Utility which is used to manage event logs and publishers..
Where:
The where command is used to search for files that match a specified pattern..
Whoami:
The whoami command is used to retrieve user name and group information on a network..
Winrm:
The winrm command is used to start the command line version of Windows Remote Management, used to manage secure communications with local and remote computers using web services..
Winrs:
The winrs command is used to open a secure command window with a remote host..
Winsat:
The winsat command starts the Windows System Assessment Tool, a program that assesses various features, attributes, and capabilities of a computer running Windows..
Wmic:
The wmic command starts the Windows Management Instrumentation Command line (WMIC), a scripting interface that simplifies the use of Windows Management Instrumentation (WMI) and systems managed via WMI..
Xcopy:
The xcopy command can copy one or more files or directory trees from one location to another.

vi/vim cheat sheet


My vi/vim cheatsheet

Cursor movement

  • h - move left
  • j - move down
  • k - move up
  • l - move right
  • w - jump by start of words (punctuation considered words)
  • W - jump by words (spaces separate words)
  • e - jump to end of words (punctuation considered words)
  • E - jump to end of words (no punctuation)
  • b - jump backward by words (punctuation considered words)
  • B - jump backward by words (no punctuation)
  • 0 - (zero) start of line
  • ^ - first non-blank character of line
  • $ - end of line
  • G - Go To command (prefix with number - 5G goes to line 5)

Note: Prefix a cursor movement command with a number to repeat it. For example, 4j moves down 4 lines.

Insert Mode - Inserting/Appending text

  • i - start insert mode at cursor
  • I - insert at the beginning of the line
  • a - append after the cursor
  • A - append at the end of the line
  • o - open (append) blank line below current line (no need to press return)
  • O - open blank line above current line
  • ea - append at end of word
  • Esc - exit insert mode

Editing

  • r - replace a single character (does not use insert mode)
  • J - join line below to the current one
  • cc - change (replace) an entire line
  • cw - change (replace) to the end of word
  • c$ - change (replace) to the end of line
  • s - delete character at cursor and subsitute text
  • S - delete line at cursor and substitute text (same as cc)
  • xp - transpose two letters (delete and paste, technically)
  • u - undo
  • . - repeat last command

Marking text (visual mode)

  • v - start visual mode, mark lines, then do command (such as y-yank)
  • V - start Linewise visual mode
  • o - move to other end of marked area
  • Ctrl+v - start visual block mode
  • O - move to Other corner of block
  • aw - mark a word
  • ab - a () block (with braces)
  • aB - a {} block (with brackets)
  • ib - inner () block
  • iB - inner {} block
  • Esc - exit visual mode

Visual commands

  • > - shift right
  • < - shift left
  • y - yank (copy) marked text
  • d - delete marked text
  • ~ - switch case

Cut and Paste

  • yy - yank (copy) a line
  • 2yy - yank 2 lines
  • yw - yank word
  • y$ - yank to end of line
  • p - put (paste) the clipboard after cursor
  • P - put (paste) before cursor
  • dd - delete (cut) a line
  • dw - delete (cut) the current word
  • x - delete (cut) current character

Exiting

  • :w - write (save) the file, but don't exit
  • :wq - write (save) and quit
  • :q - quit (fails if anything has changed)
  • :q! - quit and throw away changes

Search/Replace

  • /pattern - search for pattern
  • ?pattern - search backward for pattern
  • n - repeat search in same direction
  • N - repeat search in opposite direction
  • :%s/old/new/g - replace all old with new throughout file
  • :%s/old/new/gc - replace all old with new throughout file with confirmations

Working with multiple files

  • :e filename - Edit a file in a new buffer
  • :bnext (or :bn) - go to next buffer
  • :bprev (of :bp) - go to previous buffer
  • :bd - delete a buffer (close a file)
  • :sp filename - Open a file in a new buffer and split window
  • ctrl+ws - Split windows
  • ctrl+ww - switch between windows
  • ctrl+wq - Quit a window
  • ctrl+wv - Split windows vertically

Another good vim commands cheatsheet

C++ String references with example


C++ String Examples
constructors 1.

#include <iostream> #include <string> using namespace std; int main () { char *line = "short line for testing"; // with no arguments string s1; s1 = "Anatoliy"; cout << "s1 is: " << s1 << endl; // copy constructor string s2 (s1); cout << "s2 is: " << s2 << endl; // one argumen string s3 (line); cout << "s3 is: " << s3 << endl; // first argumen C string // second number of characters string s4 (line,10); cout << "s4 is: " << s4 << endl; // 1 - C++ string // 2 - start position // 3 - number of characters string s5 (s3,6,4); // copy word 'line' from s3 cout << "s5 is: " << s5 << endl; // 1 - number characters // 2 - character itself string s6 (15,'*'); cout << "s6 is: " << s6 << endl; // 1 - start iterator // 2 - end iterator string s7 (s3.begin(),s3.end()-5); cout << "s7 is: " << s7 << endl; // you can instantiate string with assignment string s8 = "Anatoliy"; cout << "s8 is: " << s8 << endl; return 0; } OUTPUT: // s1 is: Anatoliy // s2 is: Anatoliy // s3 is: short line for testing // s4 is: short line // s5 is: line // s6 is: *************** // s7 is: short line for te // s8 is: Anatoliy getline 1.
/* 1 getline ( intut_stream, str, delim ); Extracts characters from intut_stream and stores them in str until s.max_size() characters have been extracted, the end of file occurs, or delim is encountered, in which case delim is extracted from istr but is not stored in s 2 getline( Iter, str ) Inputs a string value for str as in the preceding func­ tion with delim = */
#include <iostream> #include <string> #include <vector> #include <fstream> using namespace std; int main () { string str; cout << "Enter string (EOL = $) : "; getline (cin, str, '$'); cout << "Str is : " << str << endl; ifstream In("data.dat"); vector v; cout << endl << "Read data from file" << endl; while ( ! In.eof() ) { getline (In, str); v.push_back(str); } copy (v.begin(),v.end(), ostream_iterator(cout,"\n")); cout << endl; return 0; } OUTPUT: // Enter string (EOL = $) : Str is : first line // second line$ // // Read data from file // file: "data.dat" // second line // last line << >> operators 1.
#include <iostream> #include <string> using namespace std; int main () { string str; cout << "Enter string for testing : "; cin >> str; cout << "\nString is : " << str << endl; cout << "Enter string for testing " << "(d to quit) : "; while ( cin >> str ) { cout << endl; cout << "String is : " << str << endl; cout << "Enter string for testing " << "(d to quit) : "; } return 0; } OUTPUT: // Enter string for testing : first // String is : first // Enter string for testing (d to quit) : second // String is : second // Enter string for testing (d to quit) : third // String is : third // Enter string for testing (d to quit) : + += = operators 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "Hello"; cout << "str is : " << str << endl; str += ","; str += ' '; cout << "str is : " << str << endl; string s; s = str + "World"; cout << "s is : " << s << endl; char ch = '!'; s += ch; cout << "s is : " << s << endl; return 0; } OUTPUT: // str is : Hello // str is : Hello, // s is : Hello, World // s is : Hello, World! append 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "Nobody is perfect"; string s = ""; // empty string char *ch = "abcdef"; // append string str at the end of s; // return s // appends at the end of s a copy of the n characters // in str, starting at position pos; if n is too // large, characters are copied only until the end // of str is reached; // returns s s.append(str,0,6); cout << "s is : " << s << endl; // appends copies of the characters in the range [inpIt1, // inpIt2] to s; returns s string::iterator inpIt1 = str.begin()+6; //start from ' is' string::iterator inpIt2 = str.end(); s.append(inpIt1,inpIt2); cout << "s is : " << s << endl; // appends three ! s.append(3,'!'); cout << "s is : " << s << endl; // appends the first n characters in ch at the end // of s; returns s s.append(ch,3); cout << "s is : " << s << endl; // appends charArray at the end of s; returns s s.append(ch,3); cout << "s is : " << s << endl; return 0; } OUTPUT: // s is : Nobody // s is : Nobody is perfect // s is : Nobody is perfect!!! // s is : Nobody is perfect!!!abc // s is : Nobody is perfect!!!abcabc assign 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "Nobody is perfect"; string s = ""; char *ch = "Robert Frost"; // assigns a copy of str to s; returns s s.assign(str); cout << "s is : " << s << endl; // assigns to s a copy of the n characters in str, start­ // ing at position 10: if n is too large, characters are // copied only until the end of str is reached: returns s s.assign(str,10,7); // perfect cout << "s is : " << s << endl; // assigns to s a string consisting of the first n charac­ // ters in ch: returns s s.assign(ch,6); cout << "s is : " << s << endl; // assigns to s a copy of ch: returns s s.assign(ch); cout << "s is : " << s << endl; // assigns to s a string consisting of the characters in // the range str.begin(), str.end(); returns s s.assign(str.begin(),str.end()); cout << "s is : " << s << endl; // assigns to s a string consisting of n copies of ch; // returns s s.assign(17,'*'); cout << "s is : " << s << endl; return 0; } OUTPUT: // s is : Nobody is perfect // s is : perfect // s is : Robert // s is : Robert Frost // s is : Nobody is perfect // s is : ***************** at 1.
// returns s[pos]
#include <iostream> #include <string> using namespace std; int main () { string s = "Nobody is perfect"; // Returns s[pos] for ( int pos = 0; pos < s.length(); ++pos ) cout << s.at(pos) << " "; cout << endl; return 0; } OUTPUT: // N o b o d y i s p e r f e c t begin 1.
// Returns an iterator positioned at the // first character in a string
#include <iostream> #include <string> using namespace std; int main () { string str = "C++ is best computer language"; string::iterator It = str.begin(); while ( It != str.end() ) { if ( *It == ' ' ) *It = '\n'; cout << *It++; } cout << endl; return 0; } OUTPUT: // C++ // is // best // computer // language c_str 1.
// returns (the base address of) a char // array containing the characters stored in s, // terminated by a null character.
#include <iostream> #include <string> using namespace std; int main () { string str = "Anatoliy"; char *ary = new char[str.length()+1]; // strcpy ( ary, str ); that is wrong way strcpy ( ary, str.c_str() ); // that is correct cout << ary << endl; return 0; } OUTPUT: // Anatoliy capacity 1.
// returns the size (of type size_type) // of the storage allocated in string
#include <iostream> #include <string> using namespace std; int main () { string str = "C++ is best computer language"; string::size_type cap; cap = str.capacity(); cout << "Capacity of str is: " << cap << endl; cout << "Size of str is : " << str.size() << endl; cout << "Length of str is : " << str.length() << endl; cout << "Resize the str for 50 character" << endl; str.resize(50); cap = str.capacity(); cout << "Capacity of str is: " << cap << endl; cout << "Size of str is : " << str.size() << endl; cout << "Length of str is : " << str.length() << endl; return 0; } OUTPUT: // Capacity of str is: 32 // Size of str is : 29 // Length of str is : 29 // Resize the str for 50 character // Capacity of str is: 64 // Size of str is : 50 // Length of str is : 50 compare 1.
#include <iostream> #include <string> using namespace std; int main () { string str1 = "string"; string str2 = "String"; string str3 = "second string"; char ch[] = "first string"; cout << "string str1 is : " << str1 << endl; cout << "string str2 is : " << str2 << endl; cout << "char ary ch is : " << ch << endl; cout << "string str3 is : " << str3 << endl; cout << endl; // compare str1 and str2 cout << "1." << endl; size_t comp = str1.compare(str2); cout << "String str1 is "; ( comp == 0 ) ? cout << "equal" : cout << "not equal"; cout << " to string str2" << endl; // compare str1 and literal string "string" cout << "2." << endl; comp = str1.compare("string"); cout << "String str1 is "; ( comp == 0 ) ? cout << "equal" : cout << "not equal"; cout << " to array of char \"string\"" << endl; // 3. and 4. doesn't work with Microsoft // Visual Studio compiler // compare str3 start from pos 7 to 5 // with str1 cout << "3." << endl; comp = str3.compare(str1,7,5); cout << "Part of string str3 is "; ( comp == 0 ) ? cout << "equal" : cout << "not equal"; cout << " to str1" << endl; // compare str3 start from pos 7 // with literal string "string" cout << "4." << endl; comp = str3.compare("string",7); cout << "Part of string str3 is "; ( comp == 0 ) ? cout << "equal" : cout << "not equal"; cout << " to C string \"string\"" << endl; // next 4 'compare' functions // doesn't work with GNU compiler cout << "5." << endl; comp = str1.compare(6,10,ch); cout << "String str1 is "; ( comp == 0 ) ? cout << "equal" : cout << "not equal"; cout << " to part of char ary \"first string\"" << endl; cout << "6." << endl; comp = str1.compare(0,3,str3); cout << "Part of str1 is "; ( comp == 0 ) ? cout << "equal" : cout << "not equal"; cout << " to string \"second string\"" << endl; cout << "7." << endl; comp = str1.compare(1,3,str2,1,3); cout << "String str1 is "; ( comp == 0 ) ? cout << "equal" : cout << "not equal"; cout << " to part of string \"second string\"" << endl; cout << "8." << endl; comp = str1.compare(1,3,str2,1,3); cout << "String str1 is "; ( comp == 0 ) ? cout << "equal" : cout << "not equal"; cout << " to part of string \"second string\"" << endl; return 0; } OUTPUT: GNU compiler // string str1 is : string // string str2 is : String // char ary ch is : first string // string str3 is : second string // // 1. // String str1 is not equal to string str2 // 2. // String str1 is equal to array of char "string" // 3. // Part of string str3 is equal to str1 // 4. // Part of string str3 is equal to C string "string" // 5. // 6. // 7. // 8. OUTPUT: Microsoft Visual Studio compiler // string str1 is : string // string str2 is : String // char ary ch is : first string // string str3 is : second string // // 1. // String str1 is not equal to string str2 // 2. // String str1 is equal to array of char "string" // 3. // 4. // 5. // String str1 is not equal to part of char ary "first // string" // 6. // Part of str1 is not equal to string "second string" // 7. // String str1 is equal to part of string "second string" // 8. // String str1 is equal to part of string "second string" // Press any key to continue copy 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "First Name: Robert"; char fname[255]; cout << "str is: " << str << endl; int n = str.find(':'); str.copy(fname, // copy to array n+1, // how many char 0); // start position from str // must terminate fname with '\0'; fname[n+1] = 0; cout << "fname is: " << fname << endl; return 0; } OUTPUT: // str is: First Name: Robert // fname is: First Name: empty 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "*******"; while ( ! str.empty() ) { cout << str << endl; str.erase(str.end()-1); } cout << endl; return 0; } OUTPUT: // ******* // ****** // ***** // **** // *** // ** // * end 1.
// returns an iterator porsitioned immediately // after the last character in string
#include <iostream> #include <string> using namespace std; int main () { string s; string str = "*************************"; size_t pos = str.length(); while ( pos ) { s.assign ( str.begin(),str.end() - pos+1); cout << s << endl; pos -= 5; } return 0; } OUTPUT: // * // ****** // *********** // **************** // ********************* erase 1.
#include <iostream> #include <string> #include <algorithm> using namespace std; int main () { string str, s; for ( char ch = 'a'; ch <= 'z'; ch++ ) str.append(1,ch); s = str; cout << "str is: " << str << endl; cout << "s is: " << str << endl; // removes 13 characters from the beginning str.erase(0,13); cout << "Erased range fron str : " << str << endl; // removes 13 characters starts from 14 str = s.erase(13,13); cout << "Erased range from s : " << str << endl; // removes one character pointed by s.begin() cout << endl << "Erase one, second character from s" << endl; s.erase(s.begin()+1); cout << "s is: " << s << endl; // removes range of characters s.erase(s.begin(),s.begin()+4); cout << "s is: " << s << endl; return 0; } OUTPUT: // str is: abcdefghijklmnopqrstuvwxyz // s is: abcdefghijklmnopqrstuvwxyz // Erased range fron str : nopqrstuvwxyz // Erased range from s : abcdefghijklm // // Erase one, second character from s // s is: acdefghijklm // s is: fghijklm find 1.
#include <iostream> #include <string> #include <algorithm> using namespace std; int main () { string str("C++ is best language"); int pos1, pos2; // size_t or size_type // work not correct // search for first string "best" inside of str // default position is 0 pos1 = str.find ("best"); cout << "Word best is found on position " << pos1+1 << endl; // if pattern is not found - return -1 pos2 = str.find ("best",pos1+1); cout << "Word best is found on position " << pos2+1 << endl; // search for first occurrence of character pos1 = str.find('g'); cout << "First character 'g' found on position " << pos1 << endl; // search for first occurrence of string string s = "is"; pos1 = str.find (s); cout << "Word 'is' is found on position " << pos1+1 << endl; return 0; } OUTPUT: // Word best is found on position 8 // Word best is found on position 0 // First character 'g' found on position 15 // Word 'is' is found on position 5 find_first_not_of 1.
#include <iostream> #include <string> using namespace std; int main () { string str("C++ is best language"); cout << "str is: " << str << endl; int n = str.find_first_not_of("aeiouAEIOU"); cout << "First consonant found at " << n+1 << " position" << endl; return 0; } OUTPUT: // str is: C++ is best language // First consonant found at 1 position find_first_not_of 2.
#include <iostream> #include <string> using namespace std; int main () { string str("C++ is best language"); cout << "str is: " << str << endl; // search first not ' ', // start from position 7 int n = str.find_first_not_of(' ',7); cout << "first not of space character " << "found at position " << n+1 << endl; return 0; } OUTPUT: // str is: C++ is best language // first not of space character found at position 8 find_first_not_of 3.
#include <iostream> #include <string> using namespace std; int main () { string str("C++ is best language"); string s = "C++"; cout << "str is: " << str << endl; // search character from pattern // using the first x chåracters in pattern. // the value position must be given int n = str.find_first_not_of("CBCD",0,3); cout << "first not 'C' is found at position " << n+1 << endl; // search first not of // pattern is string n = str.find_first_not_of(s); cout << "first not of C++ is found " << "at position " << n+1 << endl; return 0; } OUTPUT: // str is: C++ is best language // first not 'C' is found at position 2 // first not of C++ is found at position 4 find_first_of 1.
#include <iostream> #include <string> using namespace std; int main () { string str("C++ is best language"); string s = "be"; cout << "str is: " << str << endl; // search be start from position 2 // if position is ommited - default is 0 int n = str.find_first_of(s,2); cout << "first 'be' found at position " << n+1 << endl; // same as above but search for character n = str.find_first_of('l'); cout << "first character 'l' found at " << "position " << n+1 << endl; // search 'first of' for the characters in // charary char charary[] = " bea"; cout << "charary[] = \" bea\"" << endl; n = str.find_first_of(charary,0); cout << "first character from charary " << "found at position " << n+1 << endl; cout << "Note: position 4 is space" << endl; // same as above but third argumen is // number of character from which searching // starts // this variant of find_first_of dosn't // work properly with GNU compiler n = str.find_first_of(" bae",0,3); cout << "first character from charary " << "found at position " << n+1 << endl; return 0; } OUTPUT: // str is: C++ is best language // first 'be' found at position 8 // first character 'l' found at position 13 // charary[] = " bea" // first character from charary found at position 4 // Note: position 4 is space // first character from charary found at position 4 find_last_not_of 1.
#include <iostream> #include <string> using namespace std; int main () { string str("C++ is best language"); string s = "langue"; int pos = str.length()-1; cout << "str is: " << str << endl; // returns the highest position <= pos of a character // in str that does not match any charcter in s; // returns nopos if there is no such position: // npos is the default value for pos int n = str.find_last_not_of(s, pos); cout << "last_not_of 'langue' found at position " << n+1 << endl; // same as above but search for single character n = str.find_last_not_of('e'); cout << "last_not_of 'e' found at position " << n+1 << endl; char ary[] = "be"; // seawrch for occurence last_not_of // from pattern ary in str n = str.find_last_not_of(ary); cout << "last_not_of 'be' found at position " << n+1 << endl; return 0; } OUTPUT: // str is: C++ is best language // last_not_of 'langue' found at position 12 // last_not_of 'e' found at position 19 // last_not_of 'be' found at position 19 find_last_of 1.
#include <iostream> #include <string> using namespace std; int main () { string str("C++ is best language"); string s = "g"; cout << "str is: " << str << endl; cout << "s is: " << s << endl; int n = str.find_last_of(s); cout << "last_of '" << s << "' faund" << " at position " << n+1 << endl; n = str.find_last_of(' '); cout << "last_of ' ' faund" << " at position " << n+1 << endl; n = str.find_last_of(" la"); cout << "last_of \" la\" faund" << " at position " << n+1 << endl; return 0; } OUTPUT: // str is: C++ is best language // s is: g // last_of 'g' faund at position 19 // last_of ' ' faund at position 12 // last_of " la" faund at position 18 insert 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "C++ language"; string s = "is best"; char ch[] = "C++ language"; cout << "str is: " << str << endl; cout << "s is: " << s << endl; cout << "ch is: " << s << endl; // insert a copy of s into str // at position pos; string::size_type pos = 4; str.insert(pos,s); cout << "str is: " << str << endl; // insert a copy of ch into str at // the position specified by iterator // return an iterator positioned at // this copy int n = str.find('l'); str.insert(str.begin() + n,' '); cout << "str is: " << str << endl; // like above but n x copies of char str.insert(str.end(),3,'!'); cout << "str is: " << str << endl; // insert 4 char from ch into s // at the position 0 s.insert(0,ch,4); cout << "s is: " << s << endl; // insert 8 characters from str // start from position n ('langu...') // into s at position x (end string) n = str.find('l'); int x = s.length(); s.insert(x,str,n,8); cout << "s is: " << s << endl; n = s.find('l'); s.insert(s.begin()+n,' '); cout << "s is: " << s << endl; // insert range (begin - begin+7) of str // into s at position begin+4 s.insert(s.begin()+4,str.begin(),str.begin()+7); cout << "s is: " << s << endl; return 0; } OUTPUT: // str is: C++ language // s is: is best // ch is: is best // str is: C++ is bestlanguage // str is: C++ is best language // str is: C++ is best language!!! // s is: C++ is best // s is: C++ is bestlanguage // s is: C++ is best language // s is: C++ C++ is is best language length 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "C++ is best computer language"; cout << "str is: " << str << endl; cout << "Length of str is : " << str.length() << endl; return 0; } OUTPUT: // str is: C++ is best computer language // Length of str is : 29 max_size 1.
// returns a reverse iterator positioned // at the last character in string
#include <iostream> #include <string> using namespace std; int main () { string str = "C++ is best computer language"; cout << "str is: " << str << endl; cout << "max_size of str is: " << str.max_size() << endl; return 0; } OUTPUT: // str is: C++ is best computer language // max_size of str is: 4294967294 rbegin 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "C++ is best computer language"; cout << "str is: " << str << endl; // usual iterator doesn't work string::reverse_iterator It = str.rbegin(); while ( It != str.rend() ) cout << *It++; cout << endl; return 0; } OUTPUT: // str is: C++ is best computer language // egaugnal retupmoc tseb si ++C replace 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "STL is created from Dennis Ritchie"; string s1 = "was"; string s2 = "developed"; string s3 = "Stepanov alexander"; cout << "str is: " << str << endl; cout << "replace 'is' for 'was'" << endl; str.replace(4, // start position in str 2, // how many characters s1); // source for replasment cout << "str is: " << str << endl; cout <<"replace 'created' for 'developed'" << endl; int n = str.find('c'); // pos of 'created' int x = str.find("from") -1; str.replace(str.begin()+n,// start pointer str.begin()+x, // end pointer s2); // source cout << "str is: " << str << endl; cout << "replace 'Dennis' for 'alexander'" << endl; int x1 = str.find('D'); // search Dennis int x2 = str.find(' ',x1+1); // space after int y1 = s3.find("alex"); // search 'alex' int y2 = strlen("alexander"); str.replace(x1, // start position in str x2-x1, // how characters to replace s3, // source for replacement y1, // start positio from source y2); // how chracter start from y1 cout << "str is: " << str << endl; cout << "replace 'from' for 'by'" << endl; char ary[] = "bytes"; n = str.find("from"); // same variant possible with iterators // instead of number of position str.replace(n, // start position in str 4, // how many characters ary, // source 2); // first 2 characters from source cout << "str is: " << str << endl; cout << "replace 'a' for 'A' (alexander)" << endl; n = str.find("alexander"); str.replace(n, // start position in str 1, // how character(s) 1, // how many copies of character 'A'); // character for replasment cout << "str is: " << str << endl; cout << "replace 'Ritchie' for 'Stepanov'" << endl; x1 = str.find('R'); y1 = s3.find(' '); str.replace(str.begin()+x1, // start pointer str.end(), // to the end of str s3.begin(), // start pointer from source s3.begin()+y1 // end pointer from ); // source cout << "str is: " << str << endl; return 0; } OUTPUT: // str is: STL is created from Dennis Ritchie // replace 'is' for 'was' // str is: STL was created from Dennis Ritchie // replace 'created' for 'developed' // str is: STL was developed from Dennis Ritchie // replace 'Dennis' for 'alexander' // str is: STL was developed from alexander Ritchie // replace 'from' for 'by' // str is: STL was developed by alexander Ritchie // replace 'a' for 'A' (alexander) // str is: STL was developed by Alexander Ritchie // replace 'Ritchie' for 'Stepanov' // str is: STL was developed by Alexander Stepanov reverse 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "Anatoliy Urbanskiy"; cout << str.reverse() << endl; return 0; } OUTPUT: resize 1.
// if <=s.size(), truncates rightmost // character in s to make it of size n; otherwise, adds // copies of character ch to end of s to increase it size // to n, or adds a default character value (usually a // blank) if ch is omitted; return type is void
#include <iostream> #include <string> using namespace std; int main () { string str = "Alexander Stepanov"; cout << "str is: " << str << endl; cout << "size of str is: " << str.size() << endl; str.resize(11); cout << "after str.resize(11)" << endl; cout << "str is: " << str << endl; cout << "size of str is: " << str.size() << endl; str.resize(20,'.'); cout << "after str.resize(20,'.')" << endl; cout << "str is: " << str << endl; cout << "size of str is: " << str.size() << endl; return 0; } OUTPUT: // str is: Alexander Stepanov // size of str is: 18 // after str.resize(11) // str is: Alexander S // size of str is: 11 // after str.resize(9,'.') // str is: Alexander S......... // size of str is: 20 rfind 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "We go step by step to the target"; string s1 = "step"; cout << "str is: " << str << endl; cout << "s1 is: " << s1 << endl; cout << "int n1 = str.find(s1)" << endl; int n1 = str.find(s1); cout << "n1 = " << n1+1 << endl; cout << "int n2 = str.rfind(s1)" << endl; int n2 = str.rfind(s1); cout << "n2 = " << n2+1 << endl; cout << "n3 = str.rfind(s1,n2-1)" << endl; int n3 = str.rfind(s1,n2-1); cout << "n3 = " << n3+1 << endl; cout << "n1 = str.rfind('t')" << endl; n1 = str.rfind('t'); cout << "n1 = " << n1+1 << endl; cout << "n2 = str.rfind('t',n1-1)" << endl; n2 = str.rfind('t',n1-1); cout << "n2 = " << n2+1 << endl; char ch[] = "step"; cout << "char ch[] = \"step\"" << endl; cout << "n1 = str.rfind(ch)" << endl; n1 = str.rfind(ch); cout << "n1 = " << n1+1 << endl; cout << "n2 = str.rfind(\"stabc\",10,2)" << endl; n2 = str.rfind("stabc", // pattern 10, // start position 2); // for first 2 char // in pattern cout << "n2 = " << n2+1 << endl; return 0; } OUTPUT: // str is: We go step by step to the target // s1 is: step // int n1 = str.find(s1) // n1 = 7 // int n2 = str.rfind(s1) // n2 = 15 // n3 = str.rfind(s1,n2-1) // n3 = 7 // n1 = str.rfind('t') // n1 = 32 // n2 = str.rfind('t',n1-1) // n2 = 27 // char ch[] = "step" // n1 = str.rfind(ch) // n1 = 15 // n2 = str.rfind("stabc",10,2) // n2 = 7 size 1.
#include <iostream> #include <string> using namespace std; int main () { string str = "We go step by step to the target"; string::size_type size = str.size(); cout << "str is: " << str << endl; cout << "size of str = " << size << endl; return 0; } OUTPUT: // str is: We go step by step to the target // size of str = 32 substr 1.
// str.subsr(pos,n); // returns a copy of the substring consisting // of n characters from str, beginning at position pos // (default value 0); if n is too large or is omitted, // characters are copied only until the end of s is // reached
#include <iostream> #include <string> using namespace std; int main () { string str = "We go step by step to the target"; cout << "str is: " << str << endl; int n = str.find("step"); string s = str.substr(n); cout << "s is: " << s << endl; s = str.substr(n,12); cout << "s is: " << s << endl; return 0; } OUTPUT: // str is: We go step by step to the target // s is: step by step to the target // s is: step by step swap 1.
#include <iostream> #include <string> using namespace std; int main () { string str1 = "Robert"; string str2 = "Forest"; cout << "str1 is: " << str1 << endl; cout << "str2 is: " << str2 << endl; cout << endl; cout << "str1.swap(str2)" << endl; cout << endl; str1.swap(str2); cout << "str1 is: " << str1 << endl; cout << "str2 is: " << str2 << endl; return 0; } OUTPUT: // str1 is: Robert // str2 is: Forest // // str1.swap(str2) // // str1 is: Forest // str2 is: Robert