Reverse the Letters in Each Word of a String

Taking a string, reversing the letter in each word while leaving the word in its original position

I'm thinking you want to split, then map each element of the array to its reversed version then rejoin the array into a string:

def test(sentence)
sentence.split.map {|word| word.reverse}.join(" ")
end

More concise using symbol-to-proc (credit @MarkThomas in comments)

sentence.split.map(&:reverse).join " "

JavaScript reverse the order of letters for each word in a string

var string = "erehT era a tsav rebmun fo secruoser rof gninrael erom tpircsavaJ";
// you can split, reverse, join " " first and then "" too
string.split("").reverse().join("").split(" ").reverse().join(" ")

Output: "There are a vast number of resources for learning more Javascript"

Reverse the order of characters within words with five letters or more

Hy Pawel Niewolak, the issue is with your reverse function.

Depending on your requirements use that:

 public static String reverse(String s) {
String[] ori = s.split("");
String[] rev = new String[ori.length];

for (int i = 0; i < rev.length; i++) {
rev[i] = ori[rev.length - i - 1];
}
s = "";
for (String str : rev) {
s += str;
}
return s;
}
}

How can I reverse each word in a string?

What I would do is the following:

  1. Create a function that reverse only n char of a string
  2. Use that to reverse words of the original array.
  3. Words can be easily identified because are blocks of non-null and non-space chars.

Something like the following should work (note that I did not test the code) and produces the following output: nomiS tbeil !azziP

//this is basically your original function
char * reverse_n( char *name, const int len )
{
char *normal = name, *reverse = name+len;

if ( normal < reverse )
{
for ( ; normal < --reverse; ++normal )
{
char c = *normal;
*normal = *reverse;
*reverse = c;
}
}

return name;
}

char * my_reverse( char *nname)
{
char* name=nname;
while(*name)
{
char* next = name;
int l = 0;
//find the next word and its length
while(*next && *next!=' '){
next++;
l++;
}
//reverse it
reverse_n(name, l);
name=next;
//skip the space
if(*name)
name++;
}
return nname;
}

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"
---


Related Topics



Leave a reply



Submit