You are on page 1of 26

Chapter 10

_________
Character
Strings

1-1
Prog 9.1 (A): Concatenating Char Arrays
#include <stdio.h>

int main (void){

void concat (char result[],


const char str1[], int n1,
const char str2[], int n2);

const char s1[5] =


{'T', 'e', 's', 't', ' '};
const char s2[6] =
{'w', 'o', 'r', 'k', 's', '.' };

char s3[11];
int i;

concat (s3, s1, 5, s2, 6);

for ( i = 0; i < 11; ++i )


printf ("%c", s3[i]);

printf ("\n");

return 0;
}
1-2
Prog 9.1 (B): Concatenating Char Arrays

void concat (char result[],


const char str1[], int n1,
const char str2[], int n2)
{
int i, j;

// copy str1 to result

for ( i = 0; i < n1; ++i )


result[i] = str1[i];

// copy str2 to result

for ( j = 0; j < n2; ++j )


result[n1 + j] = str2[j];
}

1-3
Prog 9.2: Variable-Length Char Strings
// Count the number of characters in a VL string
#include <stdio.h>

int stringLength (const char string[]) {


int count = 0;

while ( string[count] != '\0' )


++count;

return count;
}

int main (void) {


int stringLength (const char string[]);

const char word1[] =


{'a', 's', 't', 'e', 'r', '\0'};
const char word2[] = {'a', 't', '\0'};

const char word3[] = {'a', 'w', 'e', '\0'};

printf ("%i %i %i\n", stringLength (word1),


stringLength (word2),
stringLength (word3));

return 0;
} 1-4
Prog 9.3 (A): Concat() with Variable-Length
Char Strings
#include <stdio.h>

int main (void) {

void concat (char result[],


const char str1[],
const char str2[]);

const char s1[] = { "Test " };


const char s2[] = { "works." };

char s3[20];

concat (s3, s1, s2);

printf ("%s \n", s3);

return 0;
}
1-5
Prog 9.3 (B): Concat() with Variable-Length
Char Strings

// concatenate two character strings

void concat (char result[],


const char str1[],
const char str2[]) {
int i, j;

// copy str1 to result

for ( i = 0; str1[i] != '\0'; ++i )


result[i] = str1[i];

// copy str2 to result

for ( j = 0; str2[j] != '\0'; ++j )


result[i + j] = str2[j];

// Terminate concatenated string


// with a null character

result [i + j] = '\0';
}
1-6
Prog 9.4 (A): Testing Char Strings for
Equality
#include <stdio.h>
#include <stdbool.h>

int main (void) {


bool equalStrings (const char s1[],
const char s2[]);

const char strA[] =


"string compare test";
const char strB[] = "string";

printf ("%i\n",
equalStrings (strA, strB) );
printf ("%i\n",
equalStrings (strA, strA) );
printf ("%i\n",
equalStrings (strB,
"string") );

return 0;
}

1-7
Prog 9.4 (B): Testing Char Strings for
Equality

bool equalStrings (const char s1[],


const char s2[]) {

int i = 0;
bool areEqual;

while (s1[i] == s2 [i] &&


s1[i] != '\0' &&
s2[i] != '\0') {
++i;
}

if (s1[i] == '\0' &&


s2[i] == '\0‘ )
areEqual = true;
else
areEqual = false;

return areEqual;
}
1-8
Prog 9.5: Reading Strings with scanf
#include <stdio.h>
int main (void) {

char str1 [81], str2 [81], str3 [81];

printf (“Enter the three strings:\n”);

scanf(“%s %s %s”, str1, str2, str3);

printf (“\n str1 = %s \n str2 = %s \n


str3 = %s \n”, str1, str2, str3);

return 0;
}

_________________________________________
Enter the three strings:
NAMAL Institute, Mianwali.

str1 = NAMAL
str2 = Institute,
str3 = Mianwali.

1-9
Prog 9.6 (A): Reading full lines of text, without scanf()

#include <stdio.h>
int main (void) {
int i; char line [81];
void readLine (char buffer[]);

readLine(line);
printf (“%s\n”, line);
return 0;
}

void readLine (char buffer[]) {


int i = 0; char c;
do {
c = getchar(); // stop and wait
buffer [i] = c;
i++;
}
while (c != ‘\n’);

buffer [i-1] = ‘\0’;


}
________________________________________
This is a simple line of text.
This is a simple line of text. 1-10
Prog 9.6 (B): Reading full lines of text, without scanf()

#include <stdio.h>
int main (void) {

int i; char line [81];


void readLine (char buffer[]);

for (i = 0; i < 3; ++i) {


readLine(line);
printf (“%s\n\n”, line);
}

return 0;
}

void readLine (char buffer[]) {


int i = 0; char c;

do {
c = getchar();
buffer [i++] = c;
}
while (c != ‘\n’);

buffer [i-1] = ‘\0’;


} 1-11
Prog 9.6 (C): Reading full lines of text, without scanf()

#include <stdio.h>
int main (void) {
int i; char line [81];
void readLine (char buffer[]);

readLine (line);
printf (“%s\n”, line);

return 0;
}

void readLine (char buffer[]) {


int i = 0;

while ((buffer [i] = getchar())


!= ‘\n’)
i++;

buffer [i] = ‘\0’;


}
_________________________________________
Less is more
Less is more 1-12
Prog 9.7(A): Counting words in a String
#include <stdio.h> #include <stdbool.h>
int main (void) {

const char text1 [] =


“..Tough ,99, times never ... last” ;

const char text2 [] =


“ But . . . tough people :$; do.” ;

const char text3 [] = “..a b c D e Ef” ;

int countWords (const char string[]);

printf (“Words count in text1 = %i”,


countWords(text1) );

printf (“Words count in text2 = %i”,


countWords(text2) );

printf (“Words count in text3 = %i”,


countWords(text3) );
return 0;
}
__________________________________________
Words count in text1 = 4
Words count in text2 = 4
Words count in text3 = 6
1-13
Prog 9.7(B): Counting words in a String
int countWords (const char string[]) {

bool alphabetic (const char c);

int i, wordCount = 0;
bool lookingForNextWord = true;

while (string [i] != ‘\0’) {

if (alphabetic (string[i])) {

if (lookingForNextWord == true) {
++wordCount;
lookingForNextWord = false;
}
}

else { //keep looking for next word


lookingForNextWord = true;
}

i++;
}
return wordCount;
} 1-14
Prog 9.7(B): Counting words in a String
int countWords (const char string[]) {

bool alphabetic (const char c);

int i, wordCount = 0;
bool lookingForNextWord = true;

while (string [i] != ‘\0’) {

if (alphabetic (string[i])) {

if (lookingForNextWord == true) {
++wordCount;
lookingForNextWord = false;
}
}

else { //keep looking for next word


lookingForNextWord = true;
}

i++;
}
return wordCount;
} 1-15
Prog 9.7 (C): Counting words in a String

bool alphabetic (const char c);

if ( (c >= ‘a’ && c <= ‘z’) ||


(c >= ‘A’ && c <= ‘Z’) )
return true;
else
return false;
}

1-16
Prog 9.8: Counting words in piece of text
#include <stdio.h> #include <stdbool.h>
/* insert the alphabetic(), readLine() and
countWords() functions here ---- */
// Remember the case: char buffer[100] = “”;
int main (void) {
int countWords (const char string[]);
int readLine (char buffer[]);

char text[81];
int totalWords = 0;
bool endOfText = false;

printf (“Type in your text\n”);


printf (“Press ENTER twice when done.\n”);

while (!endOfText) {
readLine(text);
//see if ENTER pressed twice
if (text [0] == ‘\0’)
endOfText = true;//text a null string
else
totalWords += countWords (text);
}

printf (“There are %i words in text.\n”,


totalWords);
return 0;
} 1-17
Prog 9.9 (A): Dictionary Lookup
// Program to use the dictionary lookup program

#include <stdio.h>
#include <stdbool.h>

struct entry
{
char word[15];
char definition[50];
};

bool equalStrings (const char s1[],


const char s2[]) {
int i = 0;
bool areEqual;

while ( s1[i] == s2 [i] &&


s1[i] != '\0' &&
s2[i] != '\0‘ )
++i;

if (s1[i] == '\0' && s2[i] == '\0' )


areEqual = true;
else
areEqual = false;

return areEqual;
}

1-18
Prog 9.9 (B): Dictionary Lookup

int lookup ( const struct entry dictionary[],


const char search[],
const int entries) {
int i;
bool equalStrings (const char s1[],
const char s2[]);

for (i = 0; i < entries; ++i )


if (equalStrings(search,
dictionary[i].word))
return i;

return -1;
}

1-19
Prog 9.9 (C): Dictionary Lookup
int main (void) {
const struct entry dictionary[100] = {
{ "aardvark", "a burrowing African mammal" },
{ "abyss", "a bottomless pit" },
{ "acumen", "mentally sharp; keen" },
{ "addle", "to become confused" },
{ "aerie", "a high nest" },
{ "affix", "to append; attach" },
{ "agar", "a jelly made from seaweed" },
{ "ahoy", "a nautical call of greeting" },
{ "aigrette", "an ornamental cluster of feathers" },
{ "ajar", "partially opened" }
};

char word[10];
int entries = 10;
int entry;
int lookup (const struct entry dictionary[],
const char search[],
const int entries);

printf ("Enter word: ");


scanf ("%14s", word);
entry = lookup (dictionary, word, entries);

if (entry != -1)
printf ("%s\n",
dictionary[entry].definition);
else
printf (“The word %s is not in my
dictionary.\n", word);
return 0;
} 1-20
Prog 9.10 (A): Dictionary Lookup using Binary Search
// Dictionary lookup program

#include <stdio.h>

struct entry
{
char word[15];
char definition[50];
};

// Function to compare two character strings

int compareStrings (const char s1[],


const char s2[]) {
int i = 0, answer;

while ( s1[i] == s2[i] &&


s1[i] != '\0‘ &&
s2[i] != '\0‘ )
++i;

if (s1[i] < s2[i])


answer = -1; /* s1 < s2 */
else if (s1[i] == s2[i])
answer = 0; /* s1 == s2 */
else
answer = 1; /* s1 > s2 */

return answer;
}
1-21
Prog 9.10 (B): Dictionary Lookup using Binary Search
// Function to look up a word inside a
dictionary

int lookup ( const struct entry dictionary[],


const char search[],
const int entries) {

int low = 0;
int high = entries - 1;
int mid, result;

int compareStrings (const char s1[],


const char s2[]);

while (low <= high) {

mid = (low + high) / 2;


result = compareStrings
(dictionary[mid].word, search);

if (result == -1)
low = mid + 1;
else if (result == 1)
high = mid - 1;
else
return mid; /* found it */
}

return -1; /* not found */


} 1-22
Prog 9.10 (C): Dictionary Lookup using Binary Search
int main (void){
const struct entry dictionary[100] = {
{ "aardvark", "a burrowing African mammal" },
{ "abyss", "a bottomless pit" },
{ "acumen", "mentally sharp; keen" },
{ "addle", "to become confused" },
{ "aerie", "a high nest" },
{ "affix", "to append; attach" },
{ "agar", "a jelly made from seaweed" },
{ "ahoy", "a nautical call of greeting" },
{ "aigrette", "an ornamental cluster of feathers" },
{ "ajar", "partially opened" }
};

int entries = 10;


char word[15];
int entry;
int lookup (const struct entry dictionary[],
const char search[],
const int entries);

printf ("Enter word: ");


scanf ("%14s", word);

entry = lookup (dictionary, word, entries);

if (entry != -1)
printf ("%s\n",
dictionary[entry].definition);
else
printf (“The word %s is not in my
dictionary.\n", word);
return 0;
1-23
}
Prog 9.11: Function to convert a string to an integer
#include <stdio.h>

int strToInt (const char string[]) {

int i, intValue, result = 0;

for (i = 0;
string[i] >= '0' && string[i] <= '9';
++i) {
intValue = string[i] - '0';
result = result * 10 + intValue;
}

return result;
}

int main (void) {

int strToInt (const char string[]);

printf ("%i\n", strToInt("245"));

printf ("%i\n", strToInt("100") + 25);

printf ("%i\n", strToInt("13x5"));

return 0;
}

1-24
Tutorial 1: Problem Solving

Write a function substring (source,


start, count, result) to extract a
portion of a character string.

Here source is the character string from


which you are extracting the substring,
start is an index number into source
indicating the first character of the substring,
count is the number of characters to be
extracted from the source string, and
result is an array of characters that is to
contain the extracted substring.

Also, have the function check that the


requested number of characters does exist
in the string; if this is not the case have the
function end the substring when it reaches
the end of the source string.

1-25
Tutorial 2: Problem Solving

If c is a lowercase character, the expression

c – ‘a’ + ‘A’

can produce the uppercase equivalent of c,


assuming an ASCII character set.

Write a main program that can call a function


named uppercase() that can convert all
lowercase letters in a string supplied as
argument to it (by the main program) into
their uppercase equivalents. Write this
uppercase() function too.

For the sake of testing, show a few examples


of calling this function in your main program.
In this testing, each time before and after
calling the function uppercase(), print
the input string and the uppercase string
returned by the uppercase() function.
1-26

You might also like