Header Ads

3.5 - Strings

Strings

  •  A set of things tied or threaded together on a thin cord

  • Contiguous sequence of characters 
  • Stores printable ASCII characters and its extension.
  • End of the string is marked with a special character, the null character '\0' 
  • '\0' is implicit in strings enclosed with “” 
  • Example: “You know, now this is what a string is!”
Examples:
char char_array[5] = {'H', 'E', 'L', 'L', 'O'};           -  Character Array
char str[6] = {'H', 'E', 'L', 'L', 'O', '\0'};                      -  String
char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};                        -  Valid
char str[6] = {“H”, “E”, “L”, “L”, “O”};                       -  Invalid
char str[6] = {“H” “E” “L” “L” “O”};                           -  Valid
char str[6] = {“HELLO”};                                           -  Valid
char str[6] = “HELLO”;                                               -  Valid
char str[] = “HELLO”;                                                 -  Valid
char *str = “HELLO”;                                                  -  Valid
Program Example1:
     #include 
    int main()
    {
        char char_array_1[5] = {'H', 'E', 'L', 'L', O'};
        char char_array_2[] = “Hello”;
        sizeof(char_array_1);
        sizeof(char_array_2);
        return 0;
    }
Output : The size of the array Is calculated So, : 5, 6

Program Example2:
int main()
{
    char *str = “Hello”;
    sizeof(str); 
   return 0;
}

Output : The size of pointer is always constant so, : 4 (32 Bit System)
  • String - Manipulations:

Examples:
char str1[6] = “Hello”;

char str2[6];

str2 = “World”;

Conclusion: Not possible to assign a string to a array since its a constant pointer.

char *str3 = “Hello”;

char *str4;

str4 = “World”;

Conclusion: Possible to assign a string to a pointer since its variable

Str1[0] = 'h'; 

Conclusion: Valid. str1 contains “hello”

Str3[0] = 'w'; 
Conclusion: Invalid. str3 might be stored in read only section. Undefined behavior

  • String - Sharing

#include <stdio.h>
int main()
{
    char *str1 = “Hello”;
    char *str2 = “Hello”;
    if (str1 == str2)
    {
        printf(“Yep, They share same space!\n”);
    }
    else
    {
        printf(“No, They are in different space\n”);
    }
    return 0; }

 What could be the above output try it yourself.. :)
  • Strings - Library Functions

No comments