term paper on string c++

Upload: raj-shah

Post on 10-Apr-2018

241 views

Category:

Documents


3 download

TRANSCRIPT

  • 8/8/2019 Term Paper on String c++

    1/22

    Written by raj 9464554250

    A

    TERM PAPER OF

    OBJECT ORIENTED CONCEPTSOn

    TOPIC:DEFINE CLASS STRING ANDIMLEMENT ALL THE FUNCTIONS

    RELATED TO STRINGS

    Submitted To: Submitted By:M/s. Raj kumarLovely Institute of RN1802A40

    Technology (POLY) Regd.No:10803550

    Jalandhar-Delhi G.T. Road (NH-1), Phagwara, Punjab (INDIA) - 144402. TEL: +91-

    1824-404404 Toll Free: 1800 102 4431 [email protected]

  • 8/8/2019 Term Paper on String c++

    2/22

    Written by raj 9464554250

    ACKNOWLEDGEMENT

    With regards I would like to thanks my Lect. M/s. who helped me in

    completing my Term Paper on the topic DEFINE CLASS STRING AND IMLEMENT ALL THE FUNCTIONS RELATED TO STRINGS. Of subject

    OBJECT ORIENTED CONCEPTS. Due to his proper guidance and under the

    shower of his eternal knowledge I was able to complete my Term Paper

    comfortably which might not be possible without his efforts.I must say thanks to my friend who helped me in the completion of my Term

    paper. I must say sorry for the errors if I have committed in my Term Paper.

    Raj kumar

    Date: ...............

  • 8/8/2019 Term Paper on String c++

    3/22

    Written by raj 9464554250

    INDEX

    Sr.no Topic Name

    I

    IntroductionII C++ Library

    a. About strcopyb. About stcmpc. About strcatd. About strlen

    III Eg. Of strcpy, strcmp and strlenIV Various string functions

    a. char *strcpy( )b. char *strncpy ( )c. char *strcat( )d. char *strncat( )e. char *strchr( )f. char *strrchr( )g. strcmp( )h. strspn( )i. strcspn( )j. strlen( )k. strpbrk( )l. strstr( )m. char *strtok( )

    V References

  • 8/8/2019 Term Paper on String c++

    4/22

    Written by raj 9464554250

    Introduction

    Strings in C++ are represented by arrays of characters. The end of the string is marked with a

    special character, the null character, which is simply the character with the value 0. Because

    C++ has no built-in facilities for manipulating entire arrays (copying them, comparing them,etc.), it also has very few built-in facilities for manipulating strings.

    In fact, C++'s only truly built-in string-handling is that it allows us to use string constants (also

    called string literals) in our code. Whenever we write a string, enclosed in double quotes, C

    automatically creates an array of characters for us, containing that string, terminated by the \0

    character. For example, we can declare and define an array of characters, and initialize it with a

    string constant:

    char string[] = "Hello, world!";

    In this case, we can leave out the dimension of the array, since the compiler can compute it for us

    based on the size of the initializer (14, including the terminating \0). This is the only case where

    the compiler sizes a string array for us, however; in other cases, it will be necessary that we

    decide how big the arrays and other data structures we use to hold strings are.

    C++ Library

    To do anything else with strings, we must typically call functions. The C++ library contains a

    few basic string manipulation functions, and to learn more about strings, we'll be looking at how

    these functions might be implemented.

    Since C never lets us assign entire arrays, we use the strcpy function to copy one string to

    another:

    #include

    char string1[] = "Hello, world!";

    char string2[20];

    strcpy(string2, string1);

  • 8/8/2019 Term Paper on String c++

    5/22

    Written by raj 9464554250

    About strcopy

    The destination string is strcpy's first argument, so that a call to strcpy mimics an assignment

    expression (with the destination on the left-hand side). Notice that we had to allocate string2 big

    enough to hold the string that would be copied to it. Also, at the top of any source file where

    we're using the standard library's string-handling functions (such as strcpy) we must include the

    line

    #include

    which contains external declarations for these functions.

    Abut stcmp

    Since C won't let us compare entire arrays, either, we must call a function to do that, too. The

    standard library's strcmp function compares two strings, and returns 0 if they are identical, or a

    negative number if the first string is alphabetically ``less than'' the second string, or a positive

    number if the first string is ``greater.'' (Roughly speaking, what it means for one string to be

    ``less than'' another is that it would come first in a dictionary or telephone book, although there

    are a few anomalies.) Here is an example:

    char string3[] = "this is";

    char string4[] = "a test";

    if(strcmp(string3, string4) == 0)

    printf("strings are equal\n");

    else printf("strings are different\n");

    This code fragment will print ``strings are different''. Notice that strcmp does not return a

    Boolean, true/false, zero/nonzero answer, so it's not a good idea to write something like

    if(strcmp(string3, string4)) ...

    because it will behave backwards from what you might reasonably expect.

    About strcat

    Another standard library function is strcat, which concatenates strings. It does notconcatenate

    two strings together and give you a third, new string; what it really does is append one string

    onto the end of another. (If it gave you a new string, it would have to allocate memory for it

  • 8/8/2019 Term Paper on String c++

    6/22

    Written by raj 9464554250

    somewhere, and the standard library string functions generally never do that for you

    automatically.) Here's an example:

    char string5[20] = "Hello, ";

    char string6[] = "world!";

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

    strcat(string5, string6);

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

    The first call to printf prints ``Hello, '', and the second one prints ``Hello, world!'', indicating that

    the contents of string6 have been tacked on to the end of string5. Notice that we declared string5

    with extra space, to make room for the appended characters.

    About strlen

    If you have a string and you want to know its length, you can call strlen, which returns the length

    of the string (i.e. the number of characters in it), not including the \0:

    char string7[] = "abc";

    int len = strlen(string7);

    printf("%d\n", len);

    Finally, you can print strings out with printf using the %s format specifier, as we've been doing

    in these examples already (e.g. printf("%s\n", string5);).

    Since a string is just an array of characters, all of the string-handling functions we've just seen

    can be written quite simply, using no techniques more complicated than the ones we already

    know. In fact, it's quite instructive to look at how these functions might be implemented. Here is

    a version of strcpy:

    Eg. Of strcpy, strcmp and strlen

    mystrcpy(char dest[], char src[])

    {

    int i = 0;

  • 8/8/2019 Term Paper on String c++

    7/22

    Written by raj 9464554250

    while(src[i] != '\0')

    {

    dest[i] = src[i];

    i++;

    }

    dest[i] = '\0';

    }

    We've called it mystrcpy instead of strcpy so that it won't clash with the version that's already in

    the standard library. Its operation is simple: it looks at characters in the src string one at a time,

    and as long as they're not \0, assigns them, one by one, to the corresponding positions in the dest

    string. When it's done, it terminates the dest string by appending a \0. (After exiting the while

    loop, i is guaranteed to have a value one greater than the subscript of the last character in src.)

    For comparison, here's a way of writing the same code, using a for loop:

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

    dest[i] = src[i];

    dest[i] = '\0';

    Yet a third possibility is to move the test for the terminating \0 character out of the for loop

    header and into the body of the loop, using an explicit if and break statement, so that we can

    perform the test after the assignment and therefore use the assignment inside the loop to copy the

    \0 to dest, too:

    for(i = 0; ; i++)

    {

    dest[i] = src[i];

    if(src[i] == '\0')

    break;

    }

    Here is a version of strcmp:

  • 8/8/2019 Term Paper on String c++

    8/22

    Written by raj 9464554250

    mystrcmp(char str1[], char str2[])

    {

    int i = 0;

    while(1)

    {

    if(str1[i] != str2[i])

    return str1[i] - str2[i];

    if(str1[i] == '\0' || str2[i] == '\0')

    return 0;

    i++;

    }

    }

    Characters are compared one at a time. If two characters in one position differ, the strings are

    different, and we are supposed to return a value less than zero if the first string (str1) is

    alphabetically less than the second string. Since characters in C are represented by their numeric

    character set values, and since most reasonable character sets assign values to characters in

    alphabetical order, we can simply subtract the two differing characters from each other: the

    expression str1[i] - str2[i] will yield a negative result if the i'th character of str1 is less than the

    corresponding character in str2. (As it turns out, this will behave a bit strangely when comparing

    upper- and lower-case letters, but it's the traditional approach, which the standard versions of

    strcmp tend to use.) If the characters are the same, we continue around the loop, unless the

    characters we just compared were (both) \0, in which case we've reached the end of both strings,

    and they were both equal. Notice that we used what may at first appear to be an infinite loop--the

    controlling expression is the constant 1, which is always true. What actually happens is that the

    loop runs until one of the two return statements breaks out of it (and the entire function). Note

    also that when one string is longer than the other, the first test will notice this (because one string

    will contain a real character at the [i] location, while the other will contain \0, and these are not

    equal) and the return value will be computed by subtracting the real character's value from 0, or

    vice versa.

  • 8/8/2019 Term Paper on String c++

    9/22

    Written by raj 9464554250

    Finally, here is a version of strlen:

    int mystrlen(char str[])

    {

    int i;

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

    {}

    return i;

    }

    In this case, all we have to do is find the \0 that terminates the string, and it turns out that thethree control expressions of the for loop do all the work; there's nothing left to do in the body.

    Therefore, we use an empty pair of braces {} as the loop body. Equivalently, we could use a null

    statement, which is simply a semicolon:

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

    Empty loop bodies can be a bit startling at first, but they're not unheard of.

    Everything we've looked at so far has come out of C's standard libraries. As one last example,

    let's write a substr function, for extracting a substring out of a larger string. We might call it like

    this:

    char string8[] = "this is a test";

    char string9[10];

    substr(string9, string8, 5, 4);

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

    The idea is that we'll extract a substring of length 4, starting at character 5 (0-based) of string8,

    and copy the substring to string9. Just as with strcpy, it's our responsibility to declare the

    destination string (string9) big enough. Here is an implementation of substr. Not surprisingly, it's

    quite similar to strcpy:

    substr(char dest[], char src[], int offset, int len)

    {

  • 8/8/2019 Term Paper on String c++

    10/22

    Written by raj 9464554250

    int i;

    for(i = 0; i < len && src[offset + i] != '\0'; i++)

    dest[i] = src[i + offset];

    dest[i] = '\0';

    }

    If you compare this code to the code for mystrcpy, you'll see that the only differences are that

    characters are fetched from src[offset + i] instead of src[i], and that the loop stops when len

    characters have been copied.

    As we may also have mentioned, there is a big difference between a character and a string, even

    a string which contains only one character (other than the \0). For example, 'A' is notthe same as

    "A". To drive home this point, let's illustrate it with a few examples.

    If you have a string:

    char string[] = "hello, world!";

    you can modify its first character by saying

    string[0] = 'H';

    Since you're replacing a character, you want a character constant, 'H'. It would notbe right to

    write

    string[0] = "H"; /* WRONG */

    because "H" is a string (an array of characters), not a single character. (The destination of the

    assignment, string[0], is a char, but the right-hand side is a string; these types don't match.)

    On the other hand, when you need a string, you must use a string. To print a single newline, you

    could call

    printf("\n");

    It would notbe correct to call

    printf('\n'); /* WRONG */

    printf always wants a string as its first argument. (As one final example, putchar wants a single

    character, so putchar('\n') would be correct, and putchar("\n") would be incorrect.)

  • 8/8/2019 Term Paper on String c++

    11/22

    Written by raj 9464554250

    We must also remember the difference between strings and integers. If we treat the character '1'

    as an integer, perhaps by saying

    int i = '1';

    we will probably notget the value 1 in i; we'll get the value of the character '1' in the machine's

    character set.

    Just as the character '1' is not the integer 1, the string "123" is not the integer 123. When we have

    a string of digits, we can convert it to the corresponding integer by calling the standard function

    atoi:

    char string[] = "123";

    int i = atoi(string);

    int j = atoi("456");

    Various string functions and their application examples

    1. char *strcpy( )y

    copies the string s2 into the character array s1. The value ofs1 is returned.y The C++ strcpy function copies a string from a source location to a destination location

    and provides a null character to terminate the string. The destination should be large

    enough to contain the string, including the null terminator, to avoid an overflow. It should

    not overlap with the source because strcpy does not allocate storage.

    y #include#include

    int main ()

    {

    char string1[]="test string";

    char string2[80];

    char string3[80];

  • 8/8/2019 Term Paper on String c++

    12/22

    Written by raj 9464554250

    char *string4;

    strcpy (string2,string1);

    strcpy (string3,"strcopy worked.");

    string4 = strcpy(string2, "strcpy return example");

    printf ("string1: %s\nstring2: %s\nstring3: %s\n",string1,string2,string3);

    printf ("string4: %s\n",string4);

    return 0;

    }

    2. char *strncpy ( )

    copies at most n characters of the string s2 into the character array s1. The value of s1 is

    returned.

    The C++ strncpy function copies a specified number of characters from a source to a destination.

    A null character is not appended to the destination, so it will only be null-terminated if the length

    of the source string is less than the number of bytes being copied.

    e.g

    int main ()

    {

    char string1[]= "strncpy test example";

    char string2[13];

    strncpy (string2,string1,12);

    string2[12]='\0';

    printf ("string2: %s\n",string2);

    return 0;

    }

    3. char *strcat( )y appends the string s2 to the end of character array s1. The first character from s2

    overwrites the '\0' ofs1. The value ofs1 is returned.

  • 8/8/2019 Term Paper on String c++

    13/22

    Written by raj 9464554250

    y The C++ strcat function is short for "string concatenate." Strcat appends a copy of asource string to a destination string. The null terminator character in the destination will

    be overwritten by the first character of the source and another null character will be

    appended to the end of the resulting new string.

    #include

    #include

    int main ()

    {

    char string1[80];

    char string2[80];char string3[80];

    strcpy (string1,"This string ");

    strcpy (string2,"Rose");

    strcpy (string3,"s smell like old shoes.");

    strcat (string1,"is concatenated.");

    strcat (string2,string3);

    printf ("string1: %s\n",string1);

    printf ("string2: %s\n",string2);

    return 0;

    }

    4. char *strncat( )y appends at most n characters of the string s2 to the end of character array s1. The first

    character from s2 overwrites the '\0' ofs1. The value ofs1 is returned.

    y The C++ strncat function appends up to a specified number of characters to a destinationstring. The null terminator character in the destination string will be overwritten by the

    first character of the source and a new null terminator will be appended to the end of the

    resulting new string.

  • 8/8/2019 Term Paper on String c++

    14/22

    Written by raj 9464554250

    y E.gint main ()

    {

    char string1[80];

    char string2[80];

    char string3[80];

    strcpy (string1,"This string ");

    strcpy (string2,"Rose");

    strcpy (string3,"s smell like old shoes.");

    strncat (string1,"is concatenated. Extra stuff", 16);

    strncat (string2,string3,40);

    printf ("string1: %s\n",string1);

    printf ("string2: %s\n",string2);

    return 0;

    }

    5. char *strchr( )y returns a pointer to the first instance of c in s. Returns a NULL pointer if c is not

    encountered in the string.

    y The C++ strchr function locates the first occurrence of a specified character in a sourcestring and returns a pointer to that location. This includes the null character so strchr also

    can be used to locate the end of a string. Strchr returns a null pointer if the specified

    character is not found.

    y E.gint main ()

    {

    char string1[] = "This is a test string";

    char * character_pointer;

    printf ("Looking for the 's' character in \"%s\"...\n",string1);

    /* initialize character_pointer to the location of the first 's' */

  • 8/8/2019 Term Paper on String c++

    15/22

    Written by raj 9464554250

    /* in string1 */

    character_pointer=strchr(string1,'s');

    while (character_pointer!=NULL)

    {

    /* convert the pointer location to the position within string1 */

    /* so it can be displayed */

    printf ("found at %d\n",character_pointer - string1 + 1);

    /* increment the pointer and search for the next 's' */

    character_pointer = strchr(character_pointer + 1,'s');

    }

    return 0;

    }

    6. char *strrchr( )y returns a pointer to the last instance of c in s. Returns a NULL pointer if c is not

    encountered in the string.

    y The C++ strrchr function searches a source string for the last occurrence of a specifiedcharacter and returns a pointer to that occurrence. If there are no matches in the source

    string, strrchr returns a null pointer. The search includes the null terminating character, so

    strrchr can also return a pointer to the end of a string

    y E.gint main ()

    {

    char string1[] = "abcd2abc3def5";

    char * character_pointer;

    /* search for the location of the last occurrence of 'c' in string1 */

    character_pointer = strrchr (string1, 'c');

    /* convert the pointers to position within string1. */

    /* Note the increment by one for a one-based positional notation */

    printf ("Last occurrence of 'c' found at %d \n", character_pointer - string1 + 1);

  • 8/8/2019 Term Paper on String c++

    16/22

    Written by raj 9464554250

    return 0;

    }

    7. strcmp( )y compares the string s1 to the string s2. The function returns 0 if they are the same, a

    number < 0 ifs1 < s2, a number > 0 ifs1 > s2.

    y The C++ strcmp function compares two strings. It returns 0 if equal each other and anonzero value that indicates which string is greater.

    y E.gint main ()

    {char testAnswer[] = "John";

    char testInput[80];

    do

    {

    printf ("What is my name? ");

    gets (testInput);

    }

    while (strcmp (testAnswer,testInput) != 0);

    puts ("That's correct!");

    return 0;

    }

    8. strncmp( )y compares up to n characters of the string s1 to the string s2. The function returns 0 if

    they are the same, a number < 0 ifs1 < s2, a number > 0 ifs1 > s2.

    y The C++ strncmp function compares a specified number of bytes between two strings. Itreturns 0 if they are equal to each other and a nonzero value to indicate which string is

    greater.

  • 8/8/2019 Term Paper on String c++

    17/22

    Written by raj 9464554250

    y E.gint main ()

    {

    char string1[][3] = { "archer" , "arrange" , "array" };

    int n;

    puts ("Looking for words beginning with arr...");

    for (n=0 ; n

  • 8/8/2019 Term Paper on String c++

    18/22

    Written by raj 9464554250

    printf ("The length of the initial numbers for string1 is %d.\n",i);

    /* string2 consists entirely of digits, so strspn returns the length of */

    /* string2. Note how the scan stops at the null terminator for string2. */

    i = strspn (string2,char_list);

    printf ("The length of the initial numbers for string2 is %d.\n",i);

    /* The first character of string3 is not a digit, so even though the */

    /* rest of string3 consists of digits, strspn returns 0.*/

    i = strspn (string3,char_list);

    printf ("The length of the initial numbers for string3 is %d.\n",i);

    return 0;

    }

    10.strcspn( )y returns the length of the longest substring ofs1 that begins at the start ofs1and contains

    none of the characters found in s2.

    y The C++ strcspn function searches a source string for the first occurrence of characters ina list and returns the number of characters read. This can include the terminating null

    character, so strcspn will return the length of the source string if it does not contain any of

    the characters for which it searches.

    y E.gint main ()

    {

    char string1[] = "abcd2";

    char char_list[] = "1234567890";

    int i;

    /* Notice how strcspn returns the number of characters scanned */

    /* before a match is found, in this case 4 */

    i = strcspn (string1,char_list);

    /* add 1 to the return value of strcspn to get the position */

    /* of the first matching character */

  • 8/8/2019 Term Paper on String c++

    19/22

    Written by raj 9464554250

    printf ("The first number in string1 is at position %d.\n",i+1);

    return 0;

    11.strlen( )y determines the length of the string s. Returns the number of characters in the string

    before the '\0'.

    y The strlen function in C++ returns the length of the given string. This length is thenumber of characters before the terminating null character

    y E.gint main ()

    {char name[80];

    printf ("What is your name?\n");

    scanf("%s",name);

    printf("Your name has %d letters.\n",strlen(name));

    return 0;

    }

    12.strpbrk( )y returns a pointer to the first instance in s1 of any character found in s2. Returns a NULL

    pointer if no characters from s2 are encountered in s1.

    y The C++ strpbrk function searches a source string for the first occurrence of characters ina list and returns a pointer to that first occurrence. If there are no matches in the source

    string, strpbrk returns a null pointer. The search does not include the null terminating

    character.

    y E.gint main ()

    {

    char string1[] = "abcd2abc3def5";

    char char_list[] = "1234567890";

  • 8/8/2019 Term Paper on String c++

    20/22

    Written by raj 9464554250

    char * character_pointer;

    printf ("numbers in '%s': ",string1);

    /* get the pointer to the first digit in string1 */

    character_pointer = strpbrk (string1, char_list);

    while (character_pointer != NULL)

    {

    /* display the digit we found */

    /* notice how we dereference the pointer to get the value */

    /* pointed to by character_pointer */

    printf ("%c " , *character_pointer);

    /* increment the pointer past the found digit */

    character_pointer = strpbrk (character_pointer +1,char_list);

    }

    printf ("\n");

    return 0;

    }

    13.strstr( )y returns a pointer to the first instance of string s2 in s1. Returns a NULL pointer ifs2 is

    not encountered in s1.

    y The C++ strstr function locates a specified substring within a source string. The scan doesnot include terminating null-characters. Strstr returns a pointer to the first occurrence of

    the substring in the source. If the substring is not found, strstr returns a null pointer. If the

    substring has zero length, strstr returns the source string.

    y E.gint main ()

    {

    char string1[] ="This is a test string";

    char * character_pointer;

    /* locate "test" within string1 using character_pointer */

  • 8/8/2019 Term Paper on String c++

    21/22

    Written by raj 9464554250

    character_pointer = strstr (string1,"test");

    /* change the first four characters of the string */

    /* pointed to by character_pointer to "long" */

    strncpy (character_pointer,"long",4);

    puts (string1);

    /* Note how an empty substring returns a pointer to the */

    /* beginning of string1 */

    character_pointer = strstr (string1,"");

    puts (character_pointer);

    /* There is no "z" in string1 so character_pointer */

    /* now becomes a null pointer. */

    character_pointer = strstr (string1, "z");

    return 0;

    }

    14.char *strtok( )y repeated calls to this function break string s1 into "tokens"--that is the string is broken

    into substrings, each terminating with a '\0', where the '\0' replaces any characters

    contained in string s2. The first call uses the string to be tokenized as s1; subsequent calls

    use NULL as the first argument.A pointer to the beginning of the current token is

    returned; NULL is returned if there are no more tokens.

    y The C++ strtok function tokenizes a string. It splits a source string into segments calledtokens that are separated by any of a specified set of characters called delimiters. Strtok

    takes the source string as an argument on its first call to scan for delimiters. It then uses

    the position after the end of the last token to scan for the next token in subsequent calls.

    y E.gint main ()

    {

    char string1[] ="- This, is a test string.";

    char * character_pointer;

  • 8/8/2019 Term Paper on String c++

    22/22

    Written by raj 9464554250

    printf ("Splitting string \"%s\" into tokens:\n",string1);

    character_pointer = strtok (string1," ,.-");

    while (character_pointer != NULL)

    {

    /* Note that the delimiters (space, comma, period and hyphen) */

    /* are not themselves tokenized. */

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

    character_pointer = strtok (NULL, " ,.-");

    }

    return 0;

    }

    References

    [1] http://www.cplusplus.com/reference/string/string/

    [2] http://www.cplusplus.com/reference/string/string/string/

    [3] http://www.cplusplus.com/reference/clibrary/cstring/

    [4] http://anaturb.net/C/string_exapm.htm

    [5] http://www.cplusplus.com/reference/clibrary/cstring/

    [6] http://www.bgsu.edu/departments/compsci/docs/string.html

    [7] http://www.yolinux.com/TUTORIALS/LinuxTutorialC++StringClass.html