Strings in C++ | Coding for Beginners | Lecture 4

 


  • Guys strings are easy to learn in coding ,believe me they are magic.
  • Be with patient and learn slowly, we can do magic with strings.
  • Strings are nothing but sentences .
  • For eg.1, string s = "coding for beginners" ;
  • In above example string word is used to decide that s can store a string .
  • We can also access each character/alphabet/symbols with the syntax variable[ index] .
  • In above example 'c' can be accessed by s[0] ,'o' can be accessed by s[1] ,......,'s'can be accessed by s[19].
  • So index of first letter in string is 0 and index of last letter is length of string-1 .
  • We can also assign these characters to a char datatype variable as shown below .
    • char letter_1 = s[2];
    • char letter_2 = s[6];
    • Here variable letter_1 stores 'd' since in eg1., alphabet/character with index 2 is d and variable letter_2 stores ' ' since in eg1., alphabet/character with index 6 is space .
    • Therefore  letter_1 = 'd' and letter_2 = ' '
  • We also have some standard function in c++ which manipulates strings and make our code easier.
  • Standard functions for strings in c++ 
  • length() : this function is used to get the length of the string . For example int n = s.lengh(); - Here in eg.,1 string s contains a string with length 20 .Hence n = 20 .
  • Here I'll provide a sample code ,please go through it.
    1. #include<bits/stdc++.h>
    2. using namespace std;
    3. int main()
    4. {
    5.            string s = "coding for beginners";
    6.            char letter_1 = s[2];
    7.            char letter_2 = s[6];
    8.            int n = s.length();
    9.            cout<<s<<endl<<letter_1<<endl<<letter_2<<endl<<n;
    10.            return 0;
    11. }
  • OUTPUT :
      • coding for beginners
      • d
      •  
      • 20
    • In above output we observed 3rd line is nothing ,it is because of white space presence in index 6.Also every line is new line because of endl in cout.

  • Here is a video with more and great explanation for this concept as well as code exexcution




  • Guy in the video we successfully produced output,

*****Don't worry if you are confused you will know everything in further concepts ,Don't give up if you are confused . Don't Panic ,be patient we will learn everything*****

***** If you have any doubts please ask in comment box*****

Guys if you have any doubts, please let me know

Post a Comment (0)
Previous Post Next Post

How to start Coding | coding for beginners | Lecture 1