S
S
sinister18272018-03-12 20:47:28
JavaScript
sinister1827, 2018-03-12 20:47:28

How to sort words in a string?

Help write a function that sorts the tape. Each number in the tape will contain some number. This figure will indicate the position that the word will take in the end.

Clarification: Numbers can be from 1 to 9. 1 will be the first word (not 0). If the tape is empty, return an empty tape. The words in the input feed will only contain valid values.
Example: . Result: . Here's what I've tried:sortString('g5et ski3lls on6 use1 your2 to4 7top')
'use1 your2 ski3lls to4 g5et on6 7top'

sortString = function(Str){
    Str = Str.split(",");
      var arr = ["1","2","3","4","5","6","7","8","9"];
        for(var n = 0; n < Str.length; n++){
        	for (var i =  0;  i < arr.length; i++) {
        	  if(Str.includes(arr[i])){
                  Str[n] = Str[i+1];
        	  }
        	}
        	
        }
    Str = Str.join();
    console.log(Str);
}


sortString("gonna2 Yo1u me4 tu3ch");

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-03-12
@sinister1827

const sortString = str => str
  .split(' ')
  .map(n => ({ word: n, i: /\d/.exec(n) }))
  .sort((a, b) => a.i - b.i)
  .map(n => n.word)
  .join(' ');

or
const sortString = str => [...Array(9)]
  .map((n, i) => str.match(RegExp(`\\w*${i + 1}\\w*`)))
  .filter(Boolean)
  .join(' ');

or
const sortString = str => Object
  .values(str
    .split(' ')
    .reduce((acc, n) => (acc[n.replace(/\D/g, '')] = n, acc), []))
  .join(' ');

S
Shimmu, 2018-07-30
@Shimmu

<?php
function sortString($str) {
if ($str != null) {
$arr = explode(" ", $str);
$arr2 = array();
foreach ($arr as $key => $value) {
preg_match('/[0-9]/', $value, $matches);
$arr2[$matches[0]] = $value;
}
ksort($arr2);
$newStr = implode(" ", $arr2);
return $newStr;
} else {
return "";
}
}
$str = "g5et ski3lls on6 use1 your2 to4 7top";
$res = sortString($str);
echo $res;
?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question