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:
- Create a function that reverse only
n
char of a string - Use that to reverse words of the original array.
- 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.
- Explode on spaces
- Separate letters from non-letters while accommodating multi-byte characters
- 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. - 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
How to Remove Attributes from an HTML Tag
How to Display Only One Country or a Specific Area in Google Maps Using the API
Get All Child, Grandchild etc Nodes Under Parent Using PHP with MySQL Query Results
Parse Error: Syntax Error, Unexpected '[', Expecting ')'
Which Tokens Can Be Parameterized in Pdo Prepared Statements
Case Insensitive Xpath Searching in PHP
Executing PHP Code Inside a .Js File
Pass Data from Jquery to PHP for an Ajax Post
Saving Wav File Recorded in Chrome to Server
How to Populate Dependable Drop-Down Using Ajax and PHP
Using PHP to Upload File and Add the Path to MySQL Database
How to Continue a Session from One Page to Another with PHP
How to Decode Eval( Gzinflate( Base64_Decode(