Reverse Letters in Each Word of a String Without Using Native Splitting or Reversing Functions

Reverse letters in each word of a string without using native splitting or reversing functions

$string = "I am a boy";

$reversed = "";
$tmp = "";
for($i = 0; $i < strlen($string); $i++) {
if($string[$i] == " ") {
$reversed .= $tmp . " ";
$tmp = "";
continue;
}
$tmp = $string[$i] . $tmp;
}
$reversed .= $tmp;

print $reversed . PHP_EOL;
>> I ma a yob

How to reverse words in a string instead of reversing the whole string?

you need to split the string by space

function reverseInPlace(str) {  var words = [];  words = str.match(/\S+/g);  var result = "";  for (var i = 0; i < words.length; i++) {     result += words[i].split('').reverse().join('') + " ";  }  return result}console.log(reverseInPlace("abd fhe kdj"))

Reverse a string in javascript without using any inbuilt function

Create a new string and add all the chars from the original string to it backwards:

function reverse1(str){
var r = "";
for(var i = str.length - 1; i >= 0; i--){
r += str.charAt(i);
}
return r;
}

Then just say:

str = reverse1(str);

Reverse the letters in each word of a string

This should work:

$words = explode(' ', $string);
$words = array_map('strrev', $words);
echo implode(' ', $words);

Or as a one-liner:

echo implode(' ', array_map('strrev', explode(' ', $string)));

Reverse the position of all letters in each word of a string that may contain multibyte characters

In an attempt to optimize for performance by reducing total function calls and reducing the number of preg_ calls, I'll demonstrate a technique with nested loops.

  1. Explode on spaces
  2. Separate letters from non-letters while accommodating multi-byte characters
  3. Iterate the matches array which contains 1 character per row (separated so that letters (movable characters) are in the [1] element and non-letters (immovable characters are in the [2] element.
  4. While traversing from left to right along the array of characters, if an immovable character is encountered, immediately append it to the current output string; if movable, seek out the latest unused movable character from the end of the matches array.

Code: (Demo) (variation without isset() calls)

$names = [
'ab1 ab2', // becomes ba1 ba2
'qwerty uçop', // becomes ytrewq poçu
'q1werty% uio*pl', // becomes y1trewq% lpo*iu
'Привет, мир!', // becomes тевирП, рим!
'Hello, dear @user_non-name, congrats100 points*@!', // olleH, raed @eman_non-resu, stragnoc100 stniop*@!
'a' // remains a
];

function swapLetterPositions($string): string {
$result = [];
foreach (explode(' ', $string) as $index => $word) {
$result[$index] = '';
$count = preg_match_all('/(\pL)|(.)/u', $word, $m, PREG_SET_ORDER);
for ($i = 0, $j = $count; $i < $count; ++$i) {
if (isset($m[$i][2])) { // immovable
$result[$index] .= $m[$i][2]; // append to string
} else { // movable from front
while (--$j >= 0) { // decrement $j and ensure that it represents an element index
if (!isset($m[$j][2])) { // movable from back
$result[$index] .= $m[$j][1]; // append to string
break;
}
}
}
}
}
return implode(' ', $result);
}

foreach ($names as $name) {
echo "\"$name\" => \"" . swapLetterPositions($name) . "\"\n---\n";
}

Output:

"ab1 ab2" => "ba1 ba2"
---
"qwerty uçop" => "ytrewq poçu"
---
"q1werty% uio*pl" => "y1trewq% lpo*iu"
---
"Привет, мир!" => "тевирП, рим!"
---
"Hello, dear @user_non-name, congrats100 points*@!" => "olleH, raed @eman_non-resu, stargnoc100 stniop*@!"
---
"a" => "a"
---

Reverse string without non letters symbol

You were really close! Your code is not working because you are applying the reversion to the whole string instead of doing it one word at a time. But just adding an extra step that splits the input string at white spaces (I assume white spaces is what defines words in your input) you'll get your desired result:

def reverse_string(st):
return ' '.join(reverse_word(word) for word in st.split())

def reverse_word(st):
stack = []
for el in st:
if el.isalpha():
stack.append(el)
result = ''
for el in st:
if el.isalpha():
result += stack.pop()
else:
result += el
return result

instr = 'b3ghcd hg#tyj%h'

print(reverse_string(instr)) # prints 'd3chgb hj#ytg%h'

NOTE:
You can pythonify your code a bit using some built in functions of list comprehension. In this case you'd replace the building of your stack.

stack = []
for el in st:
if el.isalpha():
stack.append(el)

for one of the following:

stack = [el for el in st if el.isalpha()]
or
stack = list(filter(str.isalpha, st))

Reverse a string in Java

You can use this:

new StringBuilder(hi).reverse().toString()

StringBuilder was added in Java 5. For versions prior to Java 5, the StringBuffer class can be used instead — it has the same API.

Reverse each individual word of Hello World string with Java

This should do the trick. This will iterate through each word in the source string, reverse it using StringBuilder's built-in reverse() method, and output the reversed word.

String source = "Hello World";

for (String part : source.split(" ")) {
System.out.print(new StringBuilder(part).reverse().toString());
System.out.print(" ");
}

Output:

olleH dlroW 

Notes: Commenters have correctly pointed out a few things that I thought I should mention here. This example will append an extra space to the end of the result. It also assumes your words are separated by a single space each and your sentence contains no punctuation.



Related Topics



Leave a reply



Submit