使用函数按字母顺序对字符串进行排序 [英] Sort a string alphabetically using a function

查看:198
本文介绍了使用函数按字母顺序对字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,给您一个字符串,然后您必须使用一个函数按字母顺序对该字符串进行排序.示例:

Imagine you were given a string and you had to sort that string alphabetically using a function. Example:

sortAlphabets( 'drpoklj' ); //=> returns 'djklopr'

做到这一点的最佳方法是什么?

What would be the best way to do this?

推荐答案

您可以使用数组

You can use array sort function:

var sortAlphabets = function(text) {
    return text.split('').sort().join('');
};

STEPS

  1. string转换为array
  2. 排序array
  3. array转换回string
  1. Convert string to array
  2. Sort array
  3. Convert back array to string

演示

这篇关于使用函数按字母顺序对字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆