9. Stringsx #
Created Thursday 08 April 2021
What is a str
- The last element is the ‘\0’
- strlen() does not count the ‘\0’
- sizeof() calculates the length of the array irrespective of character.
- It’s not compulsory to know the length in case of character pointers.
- A write head is very useful for in place transformations, where the EOS ro EOL may be treated the same as case end, with the next iteration stopping if we reached EOL. This helps in making the code same for every case. A special case is not required.
- cout for a char[] or char* prints every character until it hits reaches any whitespace(which are not printed). *Note: This means we cannot cout a address, it will do this for even one character, so unexpected behavior.
- cin for a char* or char[], takes input until we type a backdefaut inserts a null character(if space is left), otherwise code will give segmentation faults or SIGSEGV.
- cin works upon a temporary memory till it encounters a whitespace, then it calculates the size and copies the array elements.
- void cin.getline(charx, int n) - takes in array name(or char) and number(which includes null). So for n=27, we can store abc…z’0’.
- cin.getline(char**x*, int max_size, char delimiter=’ \0’)
http://www.cplusplus.com/doc/tutorial/ntcs/ Relation between strings and NULL terminated character arrays, they are the same! Except that strings are managed dynamically.
char nula[] =“jhwev” string nula_string = nula;// converted to string
inbuilt function: in
- strlen(char * str); for “hello”, it returns 5.
- strcmp(char* s1, har* s2).
- If it returns 0, both strings are equal, for all non zero outputs, strings are not equal.
- If +ve, then the s1 > s2. (Assuming all characters in both are of the of the same case)
- And -ve means s1, s2. (Assuming all characters in both are of the of the same case)
- strcpy(char *destination, char *source). Will copy the string source to the destination(including the null character), assuming that memory is enough for copying).
- source can be a string literal as well.
- It copies the null character too.
- strncpy(char *destination, char *source, int n). Copies n characters from source to string(i.e overwrites).
- **Does **not append the null character.
- if source is of length less than ‘n’, then it appends null to all the remaining characters.
- stringstream this is used to convert int to strings and so on.