Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What are the methods of C++ string inversion

Shulou Source: shulou.com Published: 2022-05-31 13:56:04 10月13日 Update

This article introduces the knowledge of "what are the methods of C++ string inversion". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

/ * Analysis process: assume that the passed string is a constant const string, so that the operation is more flexible, and the literal value of the string can be passed directly for reversal. The common solution is to define a new character array equal to the length of the passed string, then copy the string and place the str characters into the character array from left to right. Then use a loop to reverse * / / * characters in the character array. First, using the above solution, pass to the const type C-style character pointer, return to the char* type * / / directly use the character array assignment char* strrev1 (const char* str) {const size_t length = strlen (str) / / find the character length char * temp = new char [length]; / / create a new character array of equal length strcpy (temp,str); / / copy for (size_t I = 0; I tmp) {char t = * tmp; * tmp++ = * p; * Plam-= t;} return ret } / / is basically similar to the previous function, except that this function uses shift operations to change the character pointer to char* strrev3 (const char* str) {char* tmp = new char [strlen (str) + 1]; strcpy (tmp,str); char* ret = tmp; char* p = tmp + strlen (str)-1; while (p > tmp) {* p ^ = * tmp * tmp++ ^ = * p; * pmurf-^ = * tmp;} return ret;} / / Save a few steps and directly assign an inverted value to the newly created character array. Hehe, it is simple and clear, but the loop executes char* strrev4 (const char* str) {char* temp = new Charlen (str) several times; for (int I = 0; I c_str (); cout

Tags: Character string position array length function end type output subscript content equivalence loop code size byte copy pointer method capacity Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Technology NVidia Linux vpn