0% found this document useful (0 votes)
2 views20 pages

Computer Methods C Programming

Lecture 8 covers the concept of strings in programming, defining them as arrays of characters that terminate with a NULL character. It discusses string manipulation, input methods using getchar() and scanf, and provides examples for reading and reversing strings. The lecture also highlights string comparison, the use of the string library, and includes exercises for practical application.

Uploaded by

Thabiso Kyle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

Computer Methods C Programming

Lecture 8 covers the concept of strings in programming, defining them as arrays of characters that terminate with a NULL character. It discusses string manipulation, input methods using getchar() and scanf, and provides examples for reading and reversing strings. The lecture also highlights string comparison, the use of the string library, and includes exercises for practical application.

Uploaded by

Thabiso Kyle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

COMPUTER METHODS 1

LECTURE 8

Strings

1 / 20 Computer Methods 1 Lecture 8: Strings


Strings

A string can be defined as an array of characters


Used to store text
Some initializations on strings:
char name[]= ”fred”;
char title[] = ”Mr”;
char programme[] = ”Exact”;

2 / 20 Computer Methods 1 Lecture 8: Strings


Internal Representation of Strings

Strings terminate with NULL character, signed


by ’\0’ (ascii code 0)
This is a convention used to know where the
string ends
It means that in order to hold a string of n chars
we need an array of length n + 1
So the previous initialization is equivalent to:
char name[]= {’f’,’r’,’e’,’d’,’\0’};
char title[3] = {’M’,’r’,’\0’};
char Answer[9] = {’E’,’x’,’a’,’c’,’t’,’\0’};

3 / 20 Computer Methods 1 Lecture 8: Strings


Manipulation of NULL character
/************************************
* cm11_8_1.c -- This program *
* shows the effect of inserting \0 *
* at different parts of the *
* string *
************************************/
#include <stdio.h>
When the program is executed the re-
int main(void)
sult is:
{
char str[]="I’m a full string"; I’m a full string
printf("%s\n", str); I’m a fool string
str[7]=’o’; I’m a fool
str[8]=’o’; I’m a fool string
printf("%s\n", str);
str[11]=’\0’;
printf("%s\n", str);
str[11] = ’s’;
printf("%s\n", str);

return 0;
}

4 / 20 Computer Methods 1 Lecture 8: Strings


Reading-in strings

There are several ways of accepting strings as input from the


user
The obvious way to go is read character by character using
getchar()
getchar() - get a byte from a stdin stream

5 / 20 Computer Methods 1 Lecture 8: Strings


Example
/************************************************
* cm11_8_2.c - This program gets a string from *
* the keyboard and prints it on the screen *
************************************************/
#include <stdio.h>
#define MAX_LENGTH 10
int main(void) {

char s[MAX_LENGTH+1]; /* We need one more */


char c; /* place for the ’\0’ */
int i;

printf("Please enter a string:\n");

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


c = getchar();
if (c==’\n’) break;
s[i] = c;
}
s[i] = ’\0’; /* Terminate the string */
printf("The string you entered is - %s\n", s);

return 0;
}
6 / 20 Computer Methods 1 Lecture 8: Strings
Reading-in strings(cont’d)

A simpler way to read in a string is to use scanf


To read in a string to a variable str, write
scanf(”%s”, str);
Notice that there is no & sign

scanf reads in letters until a space or newline


(’\n’) is encountered
The maximum length can be stated in the
parentheses:
scanf(”%10s”, str);
This will read in 10 letters, plus the ’\0’ sign (so str should
have place for 11 characters)

7 / 20 Computer Methods 1 Lecture 8: Strings


Reading-in strings with scanf: Example

/***********************************************
* cm11_8_3.c - This program gets a string from*
* the keyboard and prints it on the screen *
* using scanf *
************************************************/
#include <stdio.h>
#define MAX_LENGTH 10
int main(void) {

char s[MAX_LENGTH+1]; /* We need one more */

printf("Please enter a string:\n");


scanf("%10s",s); /* Note there if & */
printf("The string you entered is - %s\n", s);

return 0;
}

The following is the result of an execution of the program:

Please enter a string:


Machine-Learning
The string you entered is - Machine-Le

8 / 20 Computer Methods 1 Lecture 8: Strings


Exercise 1

1 Write a function getLine that reads a sequence of characters,


stores them in a given array (string).
2 Write another function reverse that reverses a string
3 Write a main program that uses getLine and reverse to
read a string from the keyboard, reverses it and displays the
result on the screen.

9 / 20 Computer Methods 1 Lecture 8: Strings


Solution: getLine

/************************************************************
* function that reads a sequence of characters and stores *
* it in a given array *
************************************************************/

void getLine(char s[],int Strlen)


{
char c;
int i;
for (i=0; i<Strlen; i++) {
c = getchar();
if (c==’\n’) break;
s[i] = c;
}
s[i] = ’\0’; /* Terminate the string */
}

10 / 20 Computer Methods 1 Lecture 8: Strings


Solution: reverse

/* Find the length of a string */


int StrLen(char s[])
{
int i, len = 0;
for( i = 0; s[i]!=’\0’;i++) len++;
return len;
}

/* this function reverses a string */


void reverse(char st []) {
char c;
int i =0, len = StrLen(st);
while(i<(len/2)) {
c= st[i];
st[i]=st[len-i-1];
st[len-i-1]=c;
i++;
}
}

11 / 20 Computer Methods 1 Lecture 8: Strings


Solution : main program
/************************************************
* cm11_8_4.c - This program gets a string from *
* the keyboard, reverses it and *
* prints the result on the screen *
************************************************/
#include <stdio.h>

#define ArraySize 80
void reverse(char str[]);
void getLine(char Str[], int Strlen );

int main() {
char Str[ArraySize];
printf("\nEnter the string to be reversed ");
getLine(Str, ArraySize);

printf("\nThe string is: %s", Str);


reverse(Str);
printf("\nReversed string is: %s", Str);
getch();
return 0;
}

12 / 20 Computer Methods 1 Lecture 8: Strings


Comparing strings

We cannot just compare strings contents by ==


If we have the following declarations:
char A[6] = "World";
char B[6] = "World";
A and B are addresses of A[0] and B[0]
respectively.
A == B if and only if A and B are the same
string in memory
In order to compare their contents we must scan
them char by char

13 / 20 Computer Methods 1 Lecture 8: Strings


Example
Example: Read in 2 strings and check if they are equal
/***************************************************
* cm11_8_5.c -- Compare 2 strings *
***************************************************/
#include <stdio.h>
int main(void) {
int i;
char A[101];
char B[101];

printf("Enter first string\n");


scanf("%100s",A);
printf("Enter second string\n");
scanf("%100s",B);

for(i=0; A[i]!=’\0’ || B[i]!=’\0’; i++)


if(A[i]!=B[i]) {
printf("A is different from B!\n");
return 0;
}

printf("A and B are the same!\n");


return 0;
}
14 / 20 Computer Methods 1 Lecture 8: Strings
String library

Like in the case of stdio.h and math.h, we have a special


library for handling strings
We should insert the line #include <string.h>
Some functions:
strlen(s) - returns the length of s
strcmp(s1, s2) - compares s1 with s2
strcpy(s1, s2) - copies to contents of s2 to s1

15 / 20 Computer Methods 1 Lecture 8: Strings


Exercise 2

Problem: Write a program that:


gets an input string from the user (up to 100 chars, no white
spaces)
gets 2 characters from the user
replaces each occurrence of the first character in the string by
the second character, and prints the result.
Test:
input: ”papa”, ’p’, ’m’
output: ”mama”

16 / 20 Computer Methods 1 Lecture 8: Strings


Exercise 3

Problem: rite a function: void UpperToLower(char str[]);


The function receives an arbitrary string and converts all its
letters to lower-case letters
Demonstrate the use of your function by some example that
prints the input and output on the screen
Test:
input : ”DoMIniQue21”
output: ”dominique21”

17 / 20 Computer Methods 1 Lecture 8: Strings


Solution: UpperToLower

/* funtion that converts Upper case


letter into lower case
*/
void UpperToLower(char str[])
{
int i;
for(i=0; str[i]!=’\0’; i++)
str[i] = ((str[i] >= ’A’ && str[i] <= ’Z’)
?str[i]-’A’+’a’: str[i]);
}

18 / 20 Computer Methods 1 Lecture 8: Strings


Solution : main program(test)

/***********************************
* cm11_8_7.c -- Replacement of *
* Upper Case by Lower Case *
**********************************/
#include <stdio.h>
The following is the result of an exe-
void UpperToLower(char str[]);
cution of the program:
int main(void) {
int i; Enter the string
char Str[81]; KwaZulu-Natal
printf("Enter the string\n"); Input = KwaZulu-Natal
scanf("%80s",Str);
printf("\nInput = %s\n", Str); Output = kwazulu-natal
UpperToLower(Str);
printf("\nOutput = %s\n", Str);
return 0;
}

19 / 20 Computer Methods 1 Lecture 8: Strings


Your To Do work

1 Read your lecture 8


2 Complete practical 5

20 / 20 Computer Methods 1 Lecture 8: Strings

You might also like