avr39ripe

cppStrBasics

Sep 22nd, 2021
726
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. int strLen(const char* str)
  4. {
  5.     int len{ 0 };
  6.     for (; *str++; ++len);
  7.     //while (*str++) len++;
  8.     return len;
  9. }
  10.  
  11. char* strCpy(const char* src, char* dest)
  12. {
  13.     auto destOrig{ dest };
  14.  
  15.     while (*dest++ = *src++);
  16.  
  17.     return destOrig;
  18. }
  19.  
  20. char* strNCpy(const char* src, int maxDest, char* dest)
  21. {
  22.     auto destOrig{ dest };
  23.  
  24.     while ((--maxDest or *src) and (*dest++ = *src++));
  25.  
  26.     if (!maxDest) { *dest = '\0'; }
  27.  
  28.     return destOrig;
  29. }
  30.  
  31. int main()
  32. {
  33.     //char str[20]{ 'H','e','l','l','o','!' };
  34.     //char str[]{ "Hello!" };
  35.     char str[20]{ "Hello!" }; // char* const str
  36.  
  37.     char* dynStr{ new char[300] };
  38.     //int* dynArr{ new int[20]{1,2,3,4,5,6,7,8} }
  39.  
  40.     //dynStr = str;
  41.     std::cout << "dynStr = " << strNCpy(str, 300, dynStr) << '\n';
  42.     str[0] = 'Z';
  43.     //str = dynStr;
  44.  
  45.    
  46.     std::cout << "str = " << str << '\n';
  47.    
  48.     std::cout << "str length is: " << strLen(dynStr) << '\n';
  49.    
  50.     return 0;
  51. }
RAW Paste Data