Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is...

Post on 18-Jan-2016

222 views 0 download

transcript

Strings

Programming Applications

Strings in C

C stores a string in a block of memory. The string is terminated by the \0 character:

Arrays of characters char word [] = { 'H', 'e', 'l', 'l', 'o', '!' }; To print out the contents of the array word, you run through each

element in the array and display it using the %c format characters. To do processings of the word (copy, concatenate two words, etc)

you need to have the actual length of the character array in a separate variable !

Strings

String is an array of characters

char Name[30];

char str[20] = “Initial Value”;

char S[]= “Welcome”;

Example: string length// Function to count the number of characters in a string#include <stdio.h>

int stringLength (char string[]){int count = 0;while ( string[count] != '\0' )

++count;return count;

}int main (void) {

char word1[] = { 'a', 's', 't', 'e', 'r', '\0' };char word2[] = { 'a', 't', '\0' };char word3[] = { 'a', 'w', 'e', '\0' };printf ("%i %i %i\n", stringLength (word1),

stringLength (word2), stringLength (word3));return 0;

}

Input / Output of strings

We can use %s to read and print a string

printf(“Name is %s \n”, Name);

scanf(“%s”, str);

Initializing character stringschar word[] = "Hello!"; Is equivalent with:char word[] = { 'H', 'e', 'l', 'l', 'o', '!', '\0' };

The null string: A character string that contains no characters other than the null character

char empty[]= "";char buf[100]= ""; Initializing a very long string over several lines:char letters[] = { "abcdefghijklmnopqrstuvwxyz\ABCDEFGHIJKLMNOPQRSTUVWXYZ" }; Adjacent strings are concatenated:char letters[] = { "abcdefghijklmnopqrstuvwxyz""ABCDEFGHIJKLMNOPQRSTUVWXYZ" };

String functions The C library supplies several string-handling functions;

You don’t have to re-write them from scratch !

#include <string.h> strcat (s1, s2)

Concatenates the character string s2 to the end of s1, placing a null character at the end of the final string.The function also returns s1.

strcmp (s1, s2) Compares strings s1 and s2 and returns a value less than

zero if s1 is less than s2, equal to zero if s1 is equal to s2, and greater than zero if s1 is greater than s2.

strcpy (s1, s2) Copies the string s2 to s1, also returning s1.

strlen (s) Returns the number of characters in s, excluding the null

character.

String functions (cont.) strncat (s1, s2, n)

Copies s2 to the end of s1 until either the null character is reached or n characters have been copied, whichever occurs first. Returns s1.

strncmp (s1, s2, n) Performs the same function as strcmp, except that at most n

characters from the strings are compared. strncpy (s1, s2, n)

Copies s2 to s1 until either the null character is reached or n characters have been copied, whichever occurs first. Returns s1.

strchr (s, c) Searches the string s for the last occurrence of the character c. If

found, a pointer to the character in s is returned; otherwise, the null pointer is returned.

strstr (s1, s2) Searches the string s1 for the first occurrence of the string s2. If

found, a pointer to the start of where s2 is located inside s1 is returned; otherwise, if s2 is not located inside s1, the null pointer is returned.

String Functions

strcpy(s1, s2)

we can not use = with string

strcpy is copying s2 into s1

String Functions

strlen(S)

Return the length of string S

strcpy(S, “industrial robot”);

strlen(S) will return 16

String Functions

strcmp(s1, s2)

It is for comparison of s1 and s2

It return 0 if s1=s2

Return –ve if s1 is less than s2

Return +ve if s1 is greater than s2

String Functions

strcat(s1, s2)

It appends s2 to the end of s1

String to number conversion

// Function to convert a string to an integer – my atoi #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) {

printf ("%i\n", strToInt("245"));printf ("%i\n", strToInt("100") + 25);printf ("%i\n", strToInt("13x5"));return 0;

}

Example: string processing

#include <stdio.h>

void concat (char result[], const char str1[], const char str2[]);

int main (void){

const char s1[] = "Test " ;const char s2[] = "works." ;char s3[20];concat (s3, s1, s2);printf ("%s\n", s3);return 0;

}

Example: concatenate strings

// Function to concatenate two character stringsvoid concat (char result[], const char str1[],

const char str2[]){

int i, j;// copy str1 to resultfor ( i = 0; str1[i] != '\0'; ++i )

result[i] = str1[i];// copy str2 to resultfor ( j = 0; str2[j] != '\0'; ++j )

result[i + j] = str2[j];// Terminate the concatenated string with a null characterresult [i + j] = '\0';

}

What is the output of

char str1[10];char str2[10]=“String2”;strcpy(str1, “hi bob”);if(!strcmp(str1, str2))

printf(“Equivelent \n”);strcat(str1, “x”);printf(“%s %c \n”, str1, str1[3]);strcat(str2, “have a nice day”);printf(“%s \n”, str2);

Testing strings for equalitybool 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;

}

!!!NOT: s1==s2

Exercise

Write a program to accept string and then

count the vowels and reverses it. Vowels are

{a, e, i, o, u, A, E, I, O, U}

Example

Write a program that print the number of

occurrences of a given character c in a given

string s.

Trace the program

int pos = 1;

int count =0;

char text[40]= “Welcome”;

while (pos <= strlen(text))

{

if(text[pos]==‘e’)

{count++;

printf(“+”);}

pos++;

}

printf(“%d”, count);

Example

Write a program to accept string str. Reverses string str (for example ABC > CBA). Adds (catenates) string n to the end of string str. Removes all occurrences of characters c from string str.

Example

Write a function Mystrlen() to find the length

of given string

Character pointers A string constant: "I am a string" is an array of characters. In the internal representation, the

array is terminated with the null character '\0' so that programs can find the end. The length in storage is thus one more than the number of characters between the double quotes.

a string constant is accessed by a pointer to its first element

char *pmessage; pmessage = "now is the time"; assigns to pmessage a pointer to the character array. This

is not a string copy; only pointers are involved !

Character pointers

amessage is an array, just big enough to hold the sequence of characters and '\0' that initializes it. Individual characters within the array may be changed but amessage will always refer to the same storage.

pmessage is a pointer, initialized to point to a string constant; the pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents.

char amessage[] = "now is the time"; /* an array */char *pmessage = "now is the time"; /* a pointer */

now is the time\0

now is the time\0

amessage

pmessage

Character Pointers

String constant acts like a character pointerchar *pc = “ABCDE”; /* declare a character pointer variable */

Variable Address Valueconstant 731 ‘A’constant 732 ‘B’constant 733 ‘C’constant 734 ‘D’constant 735 ‘E’constant 736 ‘\0’pc 800 731

char s1[] = “abc”;

Variable Address Values1[0] 900 ‘a’s1[1] 901 ‘b’s1[2] 902 ‘c’s1[3] 903 ‘\0’

‘A’

‘B’

‘C’

‘D’

‘E’

‘\0’

731

732

733

734

735

736

731800

1100Example:

char s1[] = “abc”;char *s2 = “abc”;

f(){

s1[1] = ‘y’; /* OK */s2[1] = ‘y’; /* wrong (PC is OK)*/s1 = “test”; /* wrong */s2 = “test”; /* OK */

}Example:

char s3[] = “abcdef”;

f1(){

char *s = s3;*s = ‘A’; /* s3[0]=‘A’ */s = “test”;printf(“%s\n%s\n”,s,s2);

}

Character Pointers‘a’

‘b’

‘c’

‘\0’

100

101

102

103

CONSTANT MEMORY AREA (READ ONLY)

104

105

106

107

‘t’

‘e’

‘s’

‘t’

‘\0’ 108

s1[]1000

1001

1002

1003

‘a’

‘b’

‘c’

‘\0’

100800

s2

...

1100

s3[]2000

s2000

2001

2002

2003

‘a’

‘b’

‘c’

‘d’2004 ‘e’

s3[0]=‘A’2000

2001

2002

2003

‘a’

‘b’

‘c’

‘d’2004 ‘e’

Precedence of operators

*p++ increments p after fetching the character that p points to

*++p increments p before fetching the character that p points to

char *p=“hello” ;printf(“%c”,*p++); // displays h

char *p=“hello” ;printf(“%c”,*++p); // displays e

Character pointers and functions/* strcpy: copy t to s; array subscript version */void strcpy(char s[], char t[]){

int i;i = 0;while ((s[i] = t[i]) != '\0')

i++;}/* strcpy: copy t to s; pointer version */void strcpy(char *s, char *t){

int i;i = 0;while ((*s = *t) != '\0') {

s++;t++;

}}

argc and argv In environments those support C, there is a way to pass command-

line arguments or parameters to a program when it begin executing. When main is called to begin execution, it is called with two

arguments – argc and argv argc : The first (conventionally called argc) is the number of command-

line arguments the program was invoked with argv : The second (conventionally called argv) is a pointer to an array of

character strings that contain the arguments, one per string.

Example:

if echo is a program and executed on unix prompt, such as 10 <user:/home/droberts> echo hello world

Command-Line Arguments

pointer arrayargv

argc

e c h o \0

h e l l o \0

w o r l d \0null3

Command-Line ArgumentsExample: print out the arguments. ex: hello worldmain (int argc, char *argv[]){ int i; for (i = 1; i < argc; i++) printf(“%s%c”, argv[i], (i < argc-1) ? ‘ ’ : ‘\n’);}

main (int argc, char *argv[]){ while (--argc > 0) printf(“%s%c”, *++argv, (argc > 1) ? ‘ ’ : ‘\n’);}

main (int argc, char *argv[]){ while (--argc > 0) printf((argc > 1) ? “%s “ ; “%s\n“, *++argv);}

The End