Unit 5. String with Pavan Chavhan.


Hiii everyone welcome back to the "technical_spc". I'm Pavan Chavhan and with full enthusiasm let's start our unit 5 i.e. String which is also very important for learning various languages like C++, Java, Java advanced, Python and many more.


String in "c".


(a). The string can be defined as the one-dimensional array of characters terminated by a null ('\0').

(b). The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0.

(c). Declaration :-

  •  char ch[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; 
     
                                 OR

                  char ch[] = "Hello";




String functions.






Examples :-


  • Program 1 :-






  • Output :-




  • Explanation :-

You can use the scanf() function to read a string. The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).

Even though Pavan Chavhan was entered in the above program, only "Pavan" was stored in the name string. It's because there was a space after Pavan.




Also notice that we have used the code name instead of &name with scanf().

This is because name is a char array, and we know that array names decay to pointers in C.

Thus, the name in scanf() already points to the address of the first element in the string, which is why we don't need to use &.


  • Program 2 :-



  • Output :-




  • Explanation :-

Here, we have used fgets() function to read a string from the user.

fgets(name, sizeof(name), stdlin); // read string

The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the size of the name string.

To print the string, we have used puts(name);.



If you have any questions you may ask in comment below. If you enjoyed this article, share it with your friends and colleagues!




Post a Comment

0Comments

If you have any doubts, Please let me know

Post a Comment (0)