003 implement string inversion reverse, 003 string reverse
The code is simple.
// Write code to flip a C-style string. (C-style means that "abcd" must be expressed in five characters, including the end character at the end.) # include <stdio. h> # include <string. h> void swap (char & vLeft, char & vRight) {char Temp = vLeft; vLeft = vRight; vRight = Temp;} char * reverse (char * vStr) {if (vStr = NULL) {printf ("The string is NULL! "); Return NULL;} char * Start = vStr; char * End = vStr; while (* End! = '\ 0') + + End; -- End; while (Start <End) {swap (* Start ++, * End --);} return vStr ;} int main () {char Str [] = "sfssdfnnnnnn"; printf ("% s \ n", reverse (Str); return 0 ;}
Compile the void reverse_string (char * str) function. You can reverse the string function without using any library function. For example, convert "abcd" to "dcba"
Void reverse_string (char * str)
{
Char c;
Int I, j;
For (I = 0; I ++)
{
If (* (str + I) = '\ 0') break;
}
For (j = 0; j <I; j ++, I --)
{
C = * (str + j );
* (Str + j) = * (str + I );
* (Str + I) = c;
}
}
C language reverse string Problem
There are two errors, which are displayed in the comment
# Include <stdio. h>
# Include <stdlib. h>
Int main (void)
{
Int n;
Char * p;
Puts ("Enter the number of characters you want to enter :");
Scanf ("% d", & n );
// Since char * is used, it should be uniform and sizeof (int) cannot be used)
P = (char *) malloc (n * sizeof (char ));
For (int I = 0; I <n; I ++)
{
Scanf ("% c", & p [I]); // use % c to receive characters
}
Printf ("string after reverse output :");
For (I = n-1; I> = 0; I --)
{
Printf ("% c \ t", p [I]);
}
Free (p );
System ("PAUSE ");
Return 0;
}