How to reverse a C style string completely [closed]


I'd like to reverse a C style string (null-terminated) completely, i.e. including the null character.

The null character should be the first element in the reversed string.


That's actually pretty easy:

char *reversed = "";


A C string starting with a '\0' is an empty string. And unless you do things (like adding +1) with the pointer or use functions which expect memory (pointer+size) instead of strings it doesn't matter what comes behind the '\0'

If you actually needed the real string to be present in memory after the '\0': Take the function which writes your reversed string to a given memory location (void strreverse(char *dest, const char *string)). Then call it like that: char dest[ENOUGH_SPACE]; dest[0] = '\0'; strreverse(dest + 1, YOUR_STRING);


Reversing a string is actually a good task to give to a beginner, if you haven't done any programming it would require you to sit down with a piece of paper and think about how characters are stored and how you would swap them around. Also, it requires you to be careful with when you stop so that it works both with strings with an even and odd number of characters.

Hence, why don't you give it a try yourself?

However, I don't really see the point in including the null terminator in the reverse, it would only make the string look empty when used with standard string functions. Also, I hope this is not a little-endian/big-endian mixup, as endianess don't apply to strings.


void memcpy_reverse (char* dest, const char* source, size_t n) { size_t i; for(i=0; i<n; i++) { dest[i] = source[n-i-1]; } }


Here's another way.We take a pointer and make it point to the target.Then put "x" at the location pointed by the pointer.Reverse your string and then concat it with the target.Now assign '\0' to the location pointed by pointer.

WCHAR * wszStr = "Hello World"; wcscpy_s(wszTarget,256,L"x"); WCHAR *pTempNULL = wszTarget; wcscat_s(wszTarget,256,wcsrev(wszStr)/*Or Reverse you string with your algorithm*/); *pTempNULL = '\0';


Take the String. Store it in char[] array. Use 2 indexes to loop through the characters and swap them. Reverse it back to String.

I guess we can implement this using something like this in Java:

public class ReverseString { public static void main(String[] args) { String str = "a "; char[] myChar = str.toCharArray(); System.out.println(str); int p1 = 0; int p2 = myChar.length -1; while(p1<p2) { char temp = myChar[p1]; myChar[p1]= myChar[p2]; myChar[p2] = temp; p1++; p2--; } str = str.copyValueOf(myChar); System.out.println(str); } }


public static void main(String[] args) { String str = Generator.getSaltString(); str += '\0'; System.out.println("C style string to reverse: " + str + "****"); reverse(str); } private static String reverse(String str) { int length = str.length(); char[] chars = new char[length]; int j = 0; for (int i = length - 1; i >= 0; i--) { chars[j++] = str.charAt(i); } String resultStr = new String(chars); System.out.println("****" + resultStr + "********"); return resultStr; }


Check this C# code. You can see this code in action <a href="https://dotnetfiddle.net/r7yhQc" rel="nofollow">here</a>

public static string ReverseCString(string input) { char[] charArray = input.ToCharArray(); Array.Reverse(charArray); return new string (charArray); }


  • Jquery - Break/Prevent each loop
  • Is a collocated join (a-la-netezza) theoretically possible in hive?
  • Raphaeljs Substring Text attributes
  • How to add dashes into a number input field while entering the number?
  • add scrollbar in qt window?
  • multiple iron-collapse not working, expands only first
  • Sending notification from one app to another app in another device in Android
  • R - Keep log of all plots
  • Android Studio 2.0 - this version of Android Studio is incompatible with the Gradle Plugin used. Try
  • How to apply a partial derivative Gaussian kernel to an image with OpenCV?
  • Is there an easy way to associate an event with a ListViewItem?
  • SQL query to group by maximal sets of a column having inner consecutive distances below a threshold
  • How to repeat sections of a SQL query across UNIONs? (DRY in SQL)
  • C++ cout and enum representations
  • can variables be set randomly when declaring them again?
  • How to remove gaps in flexbox?
  • C# - Most efficient way to iterate through multiple arrays/list
  • Is it possible to open regedit and navigate to straight to a specific key using process.start?
  • converting text file into xml using php?
  • rspec simple example getting error on request variable in integration test
  • Unable to get column index with table.getColumn method using custom table Model
  • C: Incompatible pointer type initializing
  • custom UITableViewCell with image for highlighting
  • How to attach a node.js readable stream to a Sendgrid email?
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • Linq Objects Group By & Sum
  • Optimizing database types to compact database (SQLite)
  • Spray.io: When (not) to use non-blocking route handling?
  • AES padding and writing the ciphertext to a disk file
  • VS2008 Enable C++ Exception with SEH
  • Matplotlib draw Spline from multiple points
  • Proper folder structure for lots of source files
  • Buffer size for converting unsigned long to string
  • Load html files in TinyMce
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Change div Background jquery
  • How does Linux kernel interrupt the application?
  • Busy indicator not showing up in wpf window [duplicate]
  • reshape alternating columns in less time and using less memory
  • Why do underscore prefixed variables exist?