Wednesday, March 9, 2011

Reverse each word is a string

/********************************************************
* *
* Reverse each word is a string *
* *
* *
*********************************************************/
#include "iostream"
using namespace std;
void reverse(char *, int , int);
int main()
{
char src[] = "My name is Abc Xyz. My dog's name is Max.";

int len = strlen(src);

int s = 0; //start index of a word
int t = 0; //end index of a word

while(t < len){
while((isalpha(src[t]) || src[t] == '\'') && t < len) t++; //find the end index of a word
reverse(src,s,t-1); //reverse the word at [s, t-1]
while(!isalpha(src[t]) && t < len) t++; //find the start index of next word
s = t; // set the start index of the next word
}
cout << src << endl;


}

/****************************************
* *
* reverse a word *
* *
*****************************************/
void reverse(char *str, int s, int t)
{
char temp;
while (s < t){
temp = str[s];
str[s] = str[t];
str[t] = temp;
t--;
s++;
}

}

Thursday, January 27, 2011

C word count program

/*
Word Count Program (delimiter is the space)
Author: Anwar Mamat
Date: 1/27/2011

*/

#define LENGTH 200

#include "stdio.h"

int main()
{
char words[LENGTH] = {"The test of a first-rate intelligence is the ability to hold two opposed ideas in mind at the same time and still retain the ability to function."};

char *p = words;
int wordcount = 0;

while(*p){
//skip spaces
while(*p++ == ' ') {
//if a space is the last, terminate the loop
if(!*p) goto done;
}
//word found
wordcount++;
//skip the word
while(*p != ' ' && *p) p++;
}
done:
printf("%s\n", words);
printf("Number of words = %d\n", wordcount);
}