C Function to reverse char array string
Simplest way: Loop the string char by char and insert each char to another char array in the reverse order.
Or try this:
2)
void reverse_string(char str[])
{
char c;
char *p, *q;
p = str;
if (!p)
return;
q = p + 1;
if (*q == '\0')
return;
c = *p;
reverse_string(q);
while (*q != '\0') {
*p = *q;
p++;
q++;
}
*p = c;
return;
}
3)
if( strlen( str ) > 0 ) {
char* first = &str[ 0 ];
char* last = &str[ strlen( str ) - 1 ];
while( first < last ) {
char tmp = *first;
*first = *last;
*last = tmp;
++first;
--last;
4)
char* strrev( char* s )
{
char c;
char* s0 = s - 1;
char* s1 = s;
/* Find the end of the string */
while (*s1) ++s1;
/* Reverse it */
while (s1-- > ++s0)
{
c = *s0;
*s0 = *s1;
*s1 = c;
}
return s;
}
Reverse String C++ using char array
sizeof(str)
does not do what you expect.
Given a char *str
, sizeof(str)
will not give you the length of that string. Instead, it will give you the number of bytes that a pointer occupies. You are probably looking for strlen()
instead.
If we fixed that, we would have:
for(i=0;i<strlen(str)/2;i++)
{
char temp=str[i];
str[i]=str[strlen(str)-i-1];
str[strlen(str)-i-1]=temp;
}
This is C++, use std::swap()
In C++, if you want to swap the contents of two variables, use std::swap
instead of the temporary variable.
So instead of:
char temp=str[i];
str[i]=str[strlen(str)-i-1];
str[strlen(str)-i-1]=temp;
You would just write:
swap(str[i], str[sizeof(str) - i - 1]);
Note how much clearer that is.
You're using C++, just use std::reverse()
std::reverse(str, str + strlen(str));
Global variables
It's extremely poor practice to make variables global if they don't need to be. In particular, I'm referring to i
about this.
Executive Summary
If I was to write this function, it would look like one of the two following implementations:
void reverseChar(char* str) {
const size_t len = strlen(str);
for(size_t i=0; i<len/2; i++)
swap(str[i], str[len-i-1]);
}
void reverseChar(char* str) {
std::reverse(str, str + strlen(str));
}
When tested, both of these produce dlrow olleh
on an input of hello world
.
reversing a string array within a 2D array using pointer in c
This is what i was looking for, sorry if I didn't explain well
char* reverseOneString(char s[STRING_LENGTH]){
char temp;
char *p = &s[0];
while(*p != '\0'){
p++;
}
p--;
printf("one reverse is sending back %c\n", *p);
return p;
}
void reverseStrings(char strings[NUM_STRINGS][STRING_LENGTH])
{
char *ptr = &strings[0][0];
printf("reversing strings\n");
printf("First pointer is pointing to: %c\n", *ptr);
for (int i = 0; i < NUM_STRINGS; i++) {
int counter = 0;
char* nptr = reverseOneString(strings[i]);
while (nptr > ptr) {
printf("ptr: %c nptr: %c\n", *ptr, *nptr);
char temp = *ptr;
*ptr = *nptr;
*nptr = temp;
nptr--;
counter++;
ptr++;
while(*ptr == '\0'){
++ptr;
}
}
ptr += STRING_LENGTH - counter;
printf("this is the process value of ptr %c\n", *ptr);
printf("\n");
}
}
Reversing string using character array
Well, the error is that you kept on increasing the str
pointer and after that decreasing the end
pointer, which finally met somewhere at the middle of the string. And right after, you printed out the string which starts somewhere from the middle in reverse order. So, I would suggest to do as follows:
#include<iostream>
void rev(char *str) {
char *end;
end = str;
if(str) {
while(*end)
++end;
--end;
while(str < end) {
char temp = *str;
*str++ = *end;
*end-- = temp;
}
}
/* Don't print the string here itself */
}
int main() {
char str[500];
std::cout<<"\n Enter the string : ";
std::cin.getline(str, sizeof(str));
rev(str);
/* Print your string here */
std::cout<<"\n The reversed string is : \n";
std::cout<<str<<std::endl;
return 0;
}
OUTPUT:
Enter the string : qwertyuiop
The reversed string is :
poiuytrewq
How to reverse every string in an array of strings through a function in C?
For starters this code snippet
char **arr;
arr[0]="John";
arr[1]="Doe";
arr[2]="Programmer";
invokes undefined behavior because the pointer arr
is uninitialized and has an indeterminate value.
Moreover this approach in any case is wrong because you may not change string literals.
What you need is to declare a two-dimensional array as for example
enum { N = 11 };
//...
char arr[3][N] =
{
"John", "Doe", "Programmer"
};
In this case the function declaration will look like
void invert( char arr[][N], int n );
The enumeration must be declared before the function declaration.
Instead of the two-dimensional array you could declare an array of pointers like
char s1[] = "John";
char s2[] = "Doe";
char s3[] = "Programmer";
char * arr[3] = { s1, s2, s3 };
In this case the function declaration may be as shown in your question
void invert(char** arr, int n)
So what you need to do with minimal changes is to substitute this code snippet
char **arr;
arr[0]="John";
arr[1]="Doe";
arr[2]="Programmer";
for this code snippet
char s1[] = "John";
char s2[] = "Doe";
char s3[] = "Programmer";
char * arr[3] = { s1, s2, s3 };
Reversing char array in C programming
here you have a working example:
#include <stdio.h> // printf
#include <stdlib.h> // malloc, free
#include <string.h> // strlen
int main() {
char* s = "hello";
size_t l = strlen(s);
char* r = (char*)malloc((l + 1) * sizeof(char));
r[l] = '\0';
int i;
for(i = 0; i < l; i++) {
r[i] = s[l - 1 - i];
}
printf("normal: %s\n", s);
printf("reverse: %s\n", r);
free(r);
}
your code was wrong in length + 1
it should say length - 1
.
and you have to pay attention to the terminating '\0'
.
Related Topics
Writing Python Bindings for C++ Code That Use Opencv
Dereferencing a Pointer When Passing by Reference
Check the File-Size Without Opening File in C++
Default VS. Implicit Constructor in C++
Why Doesn't C++ Have &&= or ||= for Booleans
C++ Push Multiple Types Onto Vector
C++: Difference Between Ampersand "&" and Asterisk "*" in Function/Method Declaration
One Way of Eliminating C4251 Warning When Using Stl-Classes in the Dll-Interface
No == Operator Found While Comparing Structs in C++
Under What Circumstances Are C++ Destructors Not Going to Be Called
How to Use C++ Std::Ostream with Printf-Like Formatting
Is It Safe to Read an Integer Variable That's Being Concurrently Modified Without Locking
Is Gcc Std::Unordered_Map Implementation Slow? If So - Why
What Is the Performance Impact of Using Int64_T Instead of Int32_T on 32-Bit Systems