0% found this document useful (0 votes)
12 views34 pages

C Chapter 10 String

The document provides an overview of character strings in programming, detailing their storage, declaration, and manipulation using various functions from the character handling and string handling libraries. It explains the differences between character constants and string constants, as well as how to input strings and use functions like strlen, strcpy, and strcat. Additionally, it covers string comparison and memory functions, illustrating their usage with code examples.

Uploaded by

b.kircali55
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)
12 views34 pages

C Chapter 10 String

The document provides an overview of character strings in programming, detailing their storage, declaration, and manipulation using various functions from the character handling and string handling libraries. It explains the differences between character constants and string constants, as well as how to input strings and use functions like strlen, strcpy, and strcat. Additionally, it covers string comparison and memory functions, illustrating their usage with code examples.

Uploaded by

b.kircali55
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/ 34

Programming

Strings
Character Strings
A sequence of characters is often referred to as a
character “string”.
A string is stored in an array of type char ending with
the null character '\0 '.
Character Strings
A string containing a single character takes up 2
bytes of storage.
Character Strings
Character Strings
char str[11]="Good Day";
int i=0;
while(str[i]!=NULL)
{
i++;
}
printf("The Length is %d\n",i);

What is the length of the array ?


Character vs. String
A string constant is a sequence of characters
enclosed in double quotes.
For example, the character string:
char s1[2]="a"; //Takes two bytes of storage.
s1:
a \0

On the other hand, the character, in single quotes:


char s2= `a`; //Takes only one byte of storage.
s2:
a
Character vs. String
8.2 Fundamentals of Strings and Characters

String declarations
Declare as a character array or a variable of type char *
char color[] = "blue";
char *colorPtr = "blue";
Remember that strings represented as character arrays end with '\0'
– color has 5 elements

Inputting strings
Use scanf
scanf("%s", word);
– Copies input into word[]
– Do not need & (because a string is a pointer)
8
Remember to leave room in the array for '\0'
8.3 Character Handling Library

Character handling library


Includes functions to perform useful tests and manipulations of
character data
Each function receives a character (an int) or EOF as an argument
The following slide contains a table of all the functions in
<ctype.h>

9
8.3 Character Handling Library
Prototype Description

int isdigit( int c ) Returns true if c is a digit and false otherwise.


int isalpha( int c ) Returns true if c is a letter and false otherwise.
int isalnum( int c ) Returns true if c is a digit or a letter and false otherwise.
int isxdigit( int c ) Returns true if c is a hexadecimal digit character and false otherwise.
int islower( int c ) Returns true if c is a lowercase letter and false otherwise.
int isupper( int c ) Returns true if c is an uppercase letter; false otherwise.
int tolower( int c ) If c is an uppercase letter, tolower returns c as a lowercase letter. Otherwise, tolower
returns the argument unchanged.
int toupper( int c ) If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise, toupper
returns the argument unchanged.
int isspace( int c ) Returns true if c is a white-space character—newline ('\n'), space (' '), form feed
('\f'), carriage return ('\r'), horizontal tab ('\t'), or vertical tab ('\v')—and
false otherwise
int iscntrl( int c ) Returns true if c is a control character and false otherwise.
int ispunct( int c ) Returns true if c is a printing character other than a space, a digit, or a letter and false
otherwise.
int isprint( int c ) Returns true value if c is a printing character including space (' ') and false
otherwise.
int isgraph( int c ) Returns true if c is a printing character other than space (' ') and false otherwise.
10
// Count the number of words in a sentence with ISSPACE //
int k=0, cnt=0;
char sentence[]="c programming tutorials";
for (k=0; k< strlen(sentence); k++)
{
if (isspace(sentence[k])!=0)
{
cnt++;
}
}
printf ("\n The number of the words in the sentence=%d",cnt+1);

The strlen() function returns the length of a string.


The length is determined by the number of characters before the null termination.

char line[100]=“hello”;
printf ("%d\n", strlen(line)); 5
Example STRLEN
int main(int argc, char *argv[]) {
char nam[4]="blue";
int i=0;
while(i<5)
{
if(nam[i]=='\0’) {
printf("NULL is encountered=%c\n",nam[i]);
}
else { printf("%c\n",nam[i]); }
i++;
}
printf("Length=%d",strlen(nam));
return 0;
}
What is the output ?
int main(int argc, char *argv[]) {
char arr[]="This is first \0 and NULL also \n second";
int i=0;
while(!iscntrl(arr[i])) { printf("%c",arr[i]);i++;} This is first
printf("\n");i++;
and NULL also
while(!iscntrl(arr[i])) {printf("%c",arr[i]);i++;}
printf("\n");i++;
while(iscntrl(arr[i])) {printf("%c",arr[i]);i++;}
printf("\n");i++;
while(!iscntrl(arr[i])) {printf("%c",arr[i]);i++;} second
return 0;
}
8.4 String Conversion Functions
Conversion functions
In <stdlib.h> (general utilities library)
Convert strings of digits to integer and floating-point values
Prototype Description
double atof( const char *nPtr ) Converts the string nPtr to double.
int atoi( const char *nPtr ) Converts the string nPtr to int.
long atol( const char *nPtr ) Converts the string nPtr to long int.
double strtod( const char *nPtr, Converts the string nPtr to double.
char **endPtr )
long strtol( const char *nPtr, Converts the string nPtr to long.
char **endPtr, int base )
unsigned long strtoul( const char Converts the string nPtr to unsigned
*nPtr, char **endPtr, int base ) long.
14
char *P="0x11", *endp;
char *Ptr[]={"12","0.96","1.475 is my score"};
long d;
int res1=atoi(Ptr[0])*2; d=strtol(P,&endp,0);
float res2=atof(Ptr[1])*5; printf("%d",d);
printf("res1=%d\n",res1); printf("%s",*endp);
printf("res2=%f\n",res2);
char arr[][15]={"25","3.12","55.75 it is number like 1.12"};
char *str;
int res1=atoi(arr[0])/10;
double num=strtod(Ptr[2], &str);
float res2=atof(arr[1])*2;
printf("res1=%d\n",res1);
printf("Number=%f\n",num);
printf("The String=%s",str); printf("res2=%.2f\n",res2);

char *str;
double num=strtod(arr[2],&str);
printf("Number=%.2f\n",num);
printf("The String=%s",str);
8.5 Standard Input/Output Library Functions
Functions in <stdio.h>
Used to manipulate character and string data
Func tio n p ro to typ e Func tio n d esc rip tio n
int getchar( void ); Inputs the next character from the standard input and
returns it as an integer.
char *gets( char *s ); Inputs characters from the standard input into the array
s until a newline or end-of-file character is
encountered. A terminating null character is appended
to the array.
int putchar( int c ); Prints the character stored in c.
int puts( const char *s ); Prints the string s followed by a newline character.
int sprintf( char *s, Equivalent to printf, except the output is stored in
const char *format, ... ); the array s instead of printing it on the screen.
int sscanf( char *s, const Equivalent to scanf, except the input is read from the
16
char *format, ... ); array s instead of reading it from the keyboard.
char *s=“10 APRIL 2017";
int d,y;
char m[10];
//******* EXAMPLE sprintf ******
sprintf(m,"%s","MY NAME IS Ozi");
printf("\n\n") ;
printf("%s",m); MY NAME IS Ozi

printf("\n\n");
// ******EXAMPLE sscanf********
sscanf(s,"%d %s %d",&d,m,&y);
printf("Day=%d\n",d); Day=10
printf("Month=%s\n",m); Month= APRIL
printf("Year=%d",y); Year=2017
8.6 String Manipulation Functions of the
String Handling Library
String handling library has functions to
Manipulate string data
Search strings
Tokenize strings
Determine string length
Func tio n p ro to typ e Func tio n d e sc rip tio n
char *strcpy( char *s1, Copies string s2 into array s1. The value of s1 is
const char *s2 ) returned.
char *strncpy( char *s1, Copies at most n characters of string s2 into array s1.
const char *s2, size_t n ) The value of s1 is returned.
char *strcat( char *s1, Appends string s2 to array s1. The first character of
const char *s2 ) s2 overwrites the terminating null character of s1.
The value of s1 is returned.
char *strncat( char *s1, Appends at most n characters of string s2 to array s1.
const char *s2, size_t n ) The18first character of s2 overwrites the terminating
char src[100], dest[100];
strcpy(src, "This is My Program");
strcpy(dest, "It is Complex");
strcat(src, dest);
printf("%s\n", src);

char str1[100]="",str2[100]="";
strncpy(str1,"This is My program",8);
strncpy(str2,"Our Program is Complex",11);
strncat(str1,str2,11);
printf("%s",str1);
8.7 Comparison Functions of the String
Handling Library

Comparing strings
Computer compares numeric ASCII codes of characters in string
int strcmp( const char *s1, const char *s2 );
Compares string s1 to s2
Returns a negative number if s1 < s2, zero if s1 == s2 or a
positive number if s1 > s2
int strncmp( const char *s1, const char *s2, size_t n );
Compares up to n characters of string s1 to s2
Returns values as above
20
// strcmp // // strncmp ///
char string3[] = "this is"; int result;
char string4[] = "is this";
/* Create two arrays to hold our data */
if(strcmp(string3, string4) == 0) char example1[50];
printf("strings are equal\n"); char example2[50];
else printf("strings are different\n");
/* Copy two strings into our data arrays */
strcpy(example1, "My Name is Ozi");
strcpy(example2, "My Name is Tarkan");

/* Compare the two strings provided up to 11 characters */


// strncpy // result = strncmp(example1, example2, 11);
int i;
char B[5], A[8]="COPY PROCESS"; /* If the two strings are the same say so */
strncpy(B,A,4); if (result == 0) printf("Strings are the same\n");
for (i=0; i<4; i++ )
{
printf ("%c\n", B[i] );
}
char *strtok(char *str, const char *delim)

Parameters
•str -- The contents of this string are modified and broken into smaller strings (tokens).
•delim -- This is the C string containing the delimiters. These may vary from one call to another.
int j;
char input[] = "A bird came down the walk";
printf("Parsing the input string '%s'\n", input); Parsing the input string
char *token; A bird came down the walk
/* get the first token */
token = strtok(input, " ");
A
bird
/* walk through other tokens */
came
while(token) // or ( token != NULL )
down
{
The
puts(token); // or printf( " %s\n", token );
walk
token = strtok(NULL, " "); /* NULL must be used to get tokens from the previous string */
}
8.9 Memory Functions of the String-
handling Library

Memory Functions
In <stdlib.h>
Manipulate, compare, and search blocks of memory
Can manipulate any block of data
Pointer parameters are void *
Any pointer can be assigned to void *, and vice versa
void * cannot be dereferenced
– Each function receives a size argument specifying the number of bytes
(characters) to process

23
8.9 Memory Functions of the String-
handling Library
Prototype Description
void *memcpy( void *s1, Copies n characters from the object pointed to by s2 into the
const void *s2, object pointed to by s1. A pointer to the resulting object is
size_t n ) returned.
void *memmove( void *s1, Copies n characters from the object pointed to by s2 into the
const void *s2, object pointed to by s1. The copy is performed as if the
size_t n ) characters are first copied from the object pointed to by s2
into a temporary array, and then copied from the temporary
array into the object pointed to by s1. A pointer to the
resulting object is returned.
int memcmp( const void *s1, Compares the first n characters of the objects pointed to by
const void *s2, s1 and s2. The function returns 0, less than 0, or greater
size_t n ) than 0 if s1 is equal to, less than or greater than s2,
respectively.
void *memchr(const void *s, Locates the first occurrence of c (converted to unsigned
int c, size_t n ) char) in the first n characters of the object pointed to by s.
If c is found, a pointer to c in the object is returned.
Otherwise, 0 is returned.
void *memset( void *s, Copies c (converted to unsigned char) into the first n
int c, size_t n ) characters24 of the object pointed to by s. A pointer to the
result is returned.
// memcpy // // memmove //
char source[] = "once upon a midnight dreary...", dest[4]; char str[] = "123456789";
memcpy(dest, source, sizeof dest); puts(str);
int n; memmove(str+4, str+3, 3); puts(str);
for(n = 0; n < sizeof dest; ++n)
putchar(dest[n]);

// memcmp //
char line[100]; // memchr //
char line2[100];
strcpy(line, "aaa"); char arr[100];
strcpy(line2,"aa"); strcpy(arr, "aaabccc");

if (memcmp( line, line2, 2) == 0) if( memchr(arr,'b',strlen(arr)) == NULL )


printf ("equal\n"); printf("b not found\n");
else
if (memcmp( line, line2, 2) < 0) printf("b is found\n");
printf("less then equal\n");
printf("b is found %d\n",1+((char*)memchr(arr,'b',strlen(arr))-arr));
if (memcmp( line, line2, 2) > 0)
printf("greater then equal\n");
Some Character String Functions
double atof(const char *string);
- Converts string into a floating point value
int atoi(const char *string);
- Converts string into an int value
char *strcat(char *s1, const char *s2);
- Appends s2 onto the end of s1
char *strchr(const char *s, int c);
- Searches for first occurrence of c in s
int strcmp(const char *s1, const char *s2);
- Compares s1 to s2
char *strcpy(char *s1, const char *s2);
- Copies s2 onto s1
size_t strlen(const char *s);
- Returns the number of characters in s
char *strstr(const char *s1, const char *s2);
- Searches for s2 in s1
char *strtok(char *s1, const char *s2);
- Extracts tokens from string s1 based on token
separators in s2
Questions-1
Write a C program to find the number of letters, digits and words in a
given sentence.
Define an array called as “arr” with 100 for the sentence that is entered by the
user.
You must NOT use the function “scanf” for the input.
You must use only one WHILE loop.
You must use only the string functions for finding the letter, digit, word or length
of the given sentence.
The output is like:
ANSWER-1
int main(int argc, char *argv[]) {
char arr[100];
int i=0,numlet=0,numdig=0,numword=1;
printf("Enter a sentence\n");
gets(arr);
while(i<strlen(arr))
Tarkan 10 Numara
{
if(isalpha(arr[i])) { numlet++; }
else if(isdigit(arr[i])){numdig++;}
else if (isspace(arr[i])){numword++;}
i++;
}
printf("Letters = %d\n", numlet);
printf("Digits = %d\n", numdig);
printf("Words = %d\n", numword);
return 0;
}
Questions-2
Write a program in C to find the length of a sentence.
In the main function
Define an array called as “arr” with 100 that is entered by the user.
You must NOT use any string functions.
You must use the function gets for the input.
Invoke a function called as “FindStr” that computes the length of the given string.
In the Function;
No return any values from the function. The function must have only a parameter
Not use any array variable and only one variable.
You must use only WHILE loop.
The result is displayed as “ The length of “
The output is like:
ANSWER 2

void FindStr(char *Ptr)


void FindStr (char *); {
int main(int argc, char *argv[]) { int len=0;
char arr[100]; while(*(Ptr+len)!='\0') while(*Ptr!='\0')
int len; {
{
printf("Enter a sentence\n"); lenstr++;
len++; Ptr++;
gets(arr); } }
FindStr(arr); printf("The length of '%s' = %d",Ptr,len);
return 0; }
}
Questions-3
Write a C program whose description and functionality is given below

Reversing the contents of the given sentence below :


“ My Name is Ozi” thus and so “ Ozi is Name My”

Use FOR and WHILE loops.


Use the string functions.
ANSWER 3

int i,k,c,cs;
char s[50]="My Name is Ozi";
char arr[5]; Finding the position of the
k=0; spaces (‘ ‘) in the text and
puts(s); Keeping them into an array
for(i=0;i<strlen(s);i++)
{
if(isspace(s[i])!=0) { arr[k]=i; k++; }
}
c=strlen(arr);cs=strlen(s);
while(c>=0) As from the position of the last
{ space, print the string to the
for(k=arr[c-1];k<cs;k++) { printf("%c",s[k]); } screen and later, for the
cs=arr[c-1]; previous space and continued…
c--;
if(c==0){printf(" ");}
}
ANSWER 3- Alternative Solution
char arr[]="My Name is Ozi";
char newarr[4][100]; *newarr[4];
char *token; newarr[i]=token;
int i=0;
token=strtok(arr," ");

while(token!='\0')
0 1 2 3 4 … 99 100
{
M y ‘\0’
strcpy(newarr[i],token); N a m e ‘\0’
token=strtok(NULL," "); i s ‘\0’
i++; O z i ‘\0’
}

for(i=3;i>=0;i--){puts(newarr[i]);}
END

You might also like