c++ - reverse() and learning pointers -
i'm aware there many questions mine, reading several didn't me. because i'm new @ programming , having hard time pointers.
as exercise, i'm trying create function in c++ reverse inputted string. here function:
char* reverse(const char* t) { int j, k; char* astring = new char[100]; for(j=0, k=strlen(t)-1; j < strlen(t); j++, k--) { astring[j]=t[k]; } astring[j+1]='\0'; return astring; }
however, input doesn't reversed @ all. doing wrong?
in c++, have better, cleaner, safer, easier , more readable option - std::string
.
here simple example of function reverse()
returns reversed std::string
:
void swap(string& str, int index1, int index2) { char temp = str[index1]; str[index1] = str[index2]; str[index2] = temp; } string reverse(string str) { int size = str.size(); (int = 0; < size / 2; i++) swap (str, i, size - - 1); return str; }
Comments
Post a Comment