13 December

String processing algorithms

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main5 ()
{
int i=0;
char str[]="C++ is great.";
while (str[i]) // NUL character is false
{
if (isalpha(str[i])) printf ("character %c is alphabetic\n",str[i]);
else printf ("character %c is not alphabetic\n",str[i]);
i++;
}
// print string in all caps
i = 0;
while(str[i])
{
putchar(toupper(str[i]));
i++;
}
putchar('\n');
// output just the alphabetic characters,
// skip spaces and symbols.
i = 0;
while(str[i])
{
if(isalpha(str[i]))
{
putchar(str[i]);
}
i++;
}
putchar('\n');
// dump NUL character
//str[strlen(str)] = 'X';
//puts(str); // might go past NUL
return 0;
}

void is_palindrome(char buf[]) // buffer
{
int i = 0;
int j = strlen(buf)-1;
while( i <= j )
{
if(buf[i] != buf[j])
{
printf("%s is NOT a palindrome.\n",
buf);
return;
}
i++;
j--;
}
printf("%s IS a palindrome\n", buf);
}

int main4()
{
char s[] = "BOB";
char t[] = "CREFRC";
char v[] = "ALICE";
is_palindrome(s);
is_palindrome(t);
is_palindrome(v);
is_palindrome("ABCBA");
is_palindrome("DEFGHHGFED");
return 0;
}

Some help on A12

#include <stdio.h>
#include <string.h>
const int ROWS = 6;
const int COLS = 6;
const char BLANK = '.';
const bool ACROSS = true;
const bool DOWN = false;

// This is a program JUST to test this one function
// from the assignment:

bool does_word_fit(const char* word, char grid[ROWS][COLS],
int i, int j, bool direction)
{
int n = strlen(word);
switch(direction)
{
case ACROSS:
if(j+n <= COLS) {
// length is okay, check existing chars
int k = 0;
while(word[k])
{
if(grid[i][j+k] != BLANK &&
grid[i][j+k] != word[k])
{ // bad.
return false;
}
k++;
}
return true;
}
else return false;
break;
case DOWN:
if(i+n <= ROWS) return true;
else return false;
break;
}
}

int main()
{
char grid[ROWS][COLS];
// initialize to blanks.
for(int i = 0; i < ROWS; i++)
{
for(int j = 0; j < COLS; j++)
{
grid[i][j] = BLANK;
}
}
grid[0][1] = 'm';
grid[5][3] = 't';
printf("ant at 0,0 across: %d\n",
does_word_fit("ant", grid, 0, 0, ACROSS));
printf("ant at 3,3 down: %d\n",
does_word_fit("ant", grid, 3, 3, DOWN));
printf("ant at 4,2 down: %d\n",
does_word_fit("ant", grid, 4, 2, DOWN));
printf("ample at 0,0 across: %d\n",
does_word_fit("ample", grid, 0, 0, ACROSS));
}

©2011 Christopher League · some rights reserved · CC by-sa