How to Reverse a String in C, C++, Java, JavaScript, PHP, Python and Kotlin
Reversing a string is one of those problems that appears everywhere — coding interviews, algorithm challenges, text processing features, and even day-to-day programming tasks. It looks simple on the surface, but every programming language solves it differently, and some approaches are far cleaner than others.
In this guide we will cover how to reverse a string in seven popular programming languages — C, C++, Java, JavaScript, PHP, Python, and Kotlin — with clear code examples, explanations of how each approach works, and the common mistakes to watch out for in each language.
What Does Reversing a String Mean?
Reversing a string simply means flipping the order of its characters so that the last character becomes the first, the second-to-last becomes the second, and so on.
Input : "tipsandtricks"
Output : "skcirtdnaspit"
Under the hood, a string is just an array of characters. Reversing it means reversing that array — swapping the character at index 0 with the last index, index 1 with the second-to-last, and so on until you reach the middle.
Some languages have built-in functions that do this in one line. Others require you to implement the logic manually. Let us go through each one.
1. Reverse a String in C
C does not treat strings as first-class objects — they are simply arrays
of characters terminated by a null character (\0). The
standard library function strrev() reverses a character
array in place.
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "tipsandtricks";
strrev(str);
printf("%s\n", str);
// Output: skcirtdnaspit
return 0;
}
How it works: strrev() takes a pointer to
a character array, walks from both ends toward the middle, and swaps
characters at each step until it reaches the centre.
Note: strrev() is available in
<string.h> on Windows (MSVC, MinGW) but is
not part of the C standard library. On Linux/GCC
it may not be available. If you need a portable solution, implement
it manually using a swap loop.
Portable Manual Reverse in C
#include <stdio.h>
#include <string.h>
void reverseString(char *str) {
int left = 0;
int right = strlen(str) - 1;
char temp;
while (left < right) {
temp = str[left];
str[left] = str[right];
str[right] = temp;
left++;
right--;
}
}
int main() {
char str[] = "tipsandtricks";
reverseString(str);
printf("%s\n", str);
// Output: skcirtdnaspit
return 0;
}
This two-pointer approach works on any C compiler without relying on platform-specific functions.
2. Reverse a String in C++
C++ has a clean built-in solution through the STL
<algorithm> header. The std::reverse()
function works directly on the string using iterators:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string str = "tipsandtricks";
reverse(str.begin(), str.end());
cout << str << endl;
// Output: skcirtdnaspit
return 0;
}
How it works: str.begin() and
str.end() are iterators pointing to the start and one
past the end of the string. std::reverse() swaps elements
from both ends moving inward until the iterators meet.
This is the idiomatic C++ approach and the one you should use in any modern C++ codebase. It modifies the string in place, so no extra memory allocation is needed.
3. Reverse a String in Java
Strings in Java are immutable — you cannot modify them in place. The
standard approach is to use StringBuilder, which is
mutable and has a built-in reverse() method:
public class Main {
public static void main(String[] args) {
String str = "tipsandtricks";
str = new StringBuilder(str).reverse().toString();
System.out.println(str);
// Output: skcirtdnaspit
}
}
How it works: new StringBuilder(str)
creates a mutable sequence of characters from the original string.
.reverse() reverses it in place, and
.toString() converts it back to an immutable
String.
This is the most efficient and widely used approach in Java. Do not
attempt to reverse a string by concatenating characters in a loop
using + — that creates a new String object on every
iteration and is extremely inefficient for long strings.
4. Reverse a String in JavaScript
JavaScript does not have a built-in string reverse method, but the standard one-liner combines three array methods:
let str = "tipsandtricks";
str = str.split("").reverse().join("");
console.log(str);
// Output: skcirtdnaspit
How it works step by step:
-
str.split("")— splits the string into an array of individual characters:["t","i","p","s","a","n","d","t","r","i","c","k","s"] -
.reverse()— reverses the array in place:["s","k","c","i","r","t","d","n","a","s","p","i","t"] -
.join("")— joins the array back into a single string:"skcirtdnaspit"
Alternative — Using spread operator (ES6+)
let str = "tipsandtricks";
let reversed = [...str].reverse().join("");
console.log(reversed);
// Output: skcirtdnaspit
The spread operator [...str] also splits the string into
an array of characters. This approach handles Unicode emoji and special
characters better than split("") in some edge cases.
5. Reverse a String in PHP
PHP has the simplest solution of all — a dedicated built-in function that does exactly one thing:
<?php
$str = "tipsandtricks";
$str = strrev($str);
echo $str;
// Output: skcirtdnaspit
?>
How it works: PHP's strrev() function is
part of the core language, requires no imports, and returns the reversed
string without modifying the original variable in place (it returns a
new value). It handles standard ASCII strings perfectly.
Note for PHP developers: strrev() works
correctly for ASCII strings but may not handle multi-byte UTF-8
characters (like accented letters or emoji) correctly. For multi-byte
strings, use a manual loop with mb_strlen() and
mb_substr() instead.
6. Reverse a String in Python
Python has the most elegant syntax for string reversal thanks to its slice notation:
str = "tipsandtricks"
str = str[::-1]
print(str)
# Output: skcirtdnaspit
How it works: Python's slice syntax is
[start:stop:step]. Leaving start and
stop empty means "the entire string", and setting
step to -1 means "go backwards one character
at a time". The result is the string read from end to start.
Alternative — Using reversed() and join()
str = "tipsandtricks"
str = "".join(reversed(str))
print(str)
# Output: skcirtdnaspit
Both approaches are valid Python. The slice method
([::-1]) is more commonly used in practice because it is
shorter and more readable once you know the syntax.
7. Reverse a String in Kotlin
Kotlin has a clean built-in extension function for this:
fun main() {
val str = "tipsandtricks"
val reversed = str.reversed()
println(reversed)
// Output: skcirtdnaspit
}
How it works: Kotlin's reversed() is an
extension function on the String class that returns a new
string with characters in reverse order. It is clean, readable, and the
recommended approach in modern Kotlin.
Alternative — Recursive approach in Kotlin
fun reverse(sentence: String): String {
if (sentence.isEmpty()) return sentence
return reverse(sentence.substring(1)) + sentence[0]
}
fun main() {
val str = "tipsandtricks"
println(reverse(str))
// Output: skcirtdnaspit
}
The recursive approach is useful for understanding how recursion works
but is not recommended for production use — it creates a new stack frame
for every character and can throw a
StackOverflowError on very long strings.
Use .reversed() for any real project.
Quick Comparison — All 7 Languages
| Language | Method | In-place? | Built-in? |
|---|---|---|---|
| C | strrev() or manual swap |
✅ Yes | ⚠️ Not standard |
| C++ | std::reverse() |
✅ Yes | ✅ Yes |
| Java | StringBuilder.reverse() |
❌ Returns new | ✅ Yes |
| JavaScript | split().reverse().join() |
❌ Returns new | ✅ Yes |
| PHP | strrev() |
❌ Returns new | ✅ Yes |
| Python | [::-1] slice |
❌ Returns new | ✅ Yes |
| Kotlin | .reversed() |
❌ Returns new | ✅ Yes |
Common Mistakes to Avoid
1. Typos in Python — print vs orint
# ❌ Wrong — orint is not a function
orint(str)
# ✅ Correct
print(str)
2. Forgetting that Java strings are immutable
// ❌ Wrong — this does nothing, String has no reverse() method
String str = "tipsandtricks";
str.reverse(); // compile error
// ✅ Correct — use StringBuilder
str = new StringBuilder(str).reverse().toString();
3. Using string concatenation in a loop (Java/JavaScript)
// ❌ Inefficient — creates a new string on every iteration
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i); // BAD for long strings
}
// ✅ Use StringBuilder instead
String reversed = new StringBuilder(str).reverse().toString();
4. Using recursive reversal on long strings (Kotlin/Java)
Recursive approaches are great for learning but can cause a
StackOverflowError on strings with thousands of characters.
Always use the built-in methods for production code.
When Is String Reversal Used in Real Projects?
String reversal is not just a coding challenge exercise — it has real practical uses:
- Palindrome detection — checking if a word or phrase reads the same forwards and backwards (like "racecar" or "madam"). Compare the original string with its reverse.
- Text processing — reversing token order in a sentence, reversing word order in a line, or manipulating text for display effects.
- Cryptography basics — simple cipher techniques involve reversing strings as part of a transformation chain.
- Algorithm problems — many array and string algorithm problems reduce to a reversal sub-problem as part of their solution.
- Interview questions — reversing a string (and variations like reversing words in a sentence) is one of the most common screening questions in coding interviews across all language stacks.
Final Thought
Reversing a string is a small problem, but it teaches something important about each language — how it treats strings (mutable vs immutable), what built-in tools are available, and how to think about iterating through characters. If you are learning a new programming language, implementing string reversal from scratch (without using the built-in function) is a great first exercise.
Out of all the languages above, Python's [::-1] slice
notation is probably the most elegant — once you understand what it means,
you will never forget it. JavaScript's
split().reverse().join() chain is the most commonly seen
in interview settings. And Kotlin's .reversed() is simply
the most readable of all.
Working on a string problem and stuck on something specific? Reach out via our contact page — happy to help.
📚 You Might Also Like
- → Best Google AdSense Alternative 2026 - Monetag Review for Publishers miscellaneous
- → How to Start Freelancing as a Web Developer in 2026 (Complete Beginner's Guide) miscellaneous
- → HTTP QUERY Method (RFC 10008) — The New HTTP Method Every Developer Should Know miscellaneous
- → JavaScript Array Methods Cheat Sheet — Complete Guide with Example javascript
- → MyLync — Best Free Linktree Alternative for Developers, Creators & Businesses miscellaneous