Pages

Sunday, October 22, 2017

Easy tutorial for C / C ++ - string 1

Easy tutorial for C / C ++ - string 1

string :

- A string is a collection of characters or a one-dimensional array of single characters (char). Another condition is that the string must end with a null character ('\ 0').

note:

The null character is different from the space character that occur when you press the space bar. (The null character's ASCII code value is 0 and the space character is 32.)

For example, the string "hello" is composed of characters such as h, e, l, l, o and the last null character ('\ 0').

- Let's look at the string through a one-dimensional array of single character types. Single character types are represented by char, and quotation marks (') are used when storing characters.

Ex) char chT = 'A';

- The string "hello" can be initialized to a one-dimensional array as follows:

char chT[] = {'h', 'e', 'l', 'l','o','\0'};
  : At the end, '\ 0' is written to indicate that it is a string. You also need to prepare space for the '\ 0' character.

or

char chT[] = "hello";

- Let's look at a simple example.

Example Code

#include <iostream>
using namespace std;

int main() {
     char chT[] = "hello";
     cout << " chT = " << chT << endl ;
     cout << " & chT[0] = " << & chT[0] << endl ;
     cout << endl;
     cout << " chT + 1 = " << chT + 1 << endl ;
     cout << " & chT[1] = " << & chT[1] << endl ;
     cout << endl;
     cout << " chT + 2 = " << chT + 2 << endl ;
     cout << " & chT[2] = " << & chT[2] << endl ;
     return 0;
}

- The string 'chT' is defined and the string "hello" is  assigned to the 'chT'.

- Let's print out the names of strings 'chT' and '& chT [0]'. When I reviewed it in the array, I said the name of the array was the starting address value. Let's see if a string gives the same result.

- Also, let's check results for 'chT + 1' and 'chT + 2'.

results :

 chT = hello
 & chT[0] = hello

 chT + 1 = ello
 & chT[1] = ello

 chT + 2 = llo
 & chT[2] = llo

- 'chT' is the name of the array and represents the starting address value of the array. However, as a result of 'chT', a string called hello was output instead of the start address value. If the << operator of cout encounters a string address, it prints the characters until it encounters a null character. '& chT [0]', which means the start address of the array, also prints the string hello.

- 'chT + 1' is the address of the second element. The character at the second address of 'hello' is 'e'. So 'ello' is printed. '& chT [1]' gave the same result.

- 'chT + 2' is the address of the third element. So 'llo' is printed.

No comments:

Post a Comment