字符串类的扩展功能

时间:2018-07-07 15:40:49

标签: kotlin kotlin-extension

我想创建一个扩展函数String,该扩展函数接受一个String并返回一个新的String,其中第一个字符为字符,但按升序排序。我怎样才能做到这一点?我是Kotlin的新手。

5 个答案:

答案 0 :(得分:4)

fun String.ascending() = String(toCharArray().sortedArray())

然后:

println("14q36w25e".ascending())  // output "123456eqw"

答案 1 :(得分:2)

您可以结合使用内置的扩展程序来快速完成此操作:

fun String.sortedAlphabetically() = toCharArray().apply { sort() }

首先获得基础字符数组,然后将排序应用于该数组并返回它。您可以根据需要随意投射结果.toString()

答案 2 :(得分:2)

扩展功能,用于按升序打印字符串中的字符

方法1:

fun String.sortStringAlphabetically() = toCharArray().sortedArray())

方法2:

fun String.sortStringAlphabetically() = toCharArray().sortedArrayDescending().reversedArray()

方法3:

fun String.sortStringAlphabetically() = toCharArray().sorted().joinToString(""))

方法4:

fun String.sortStringAlphabetically() = toCharArray().sortedBy{ it }.joinToString(""))

然后您可以通过以下代码使用此扩展功能:

fun main(args: Array<String>) {
    print("41hjhfaf".sortStringAlphabetically())
}

输出:14affhhj

答案 3 :(得分:1)

我还有一个:

def recipe_create(request):
if request.method == 'GET':
    form = RecipeForm(request.POST or None, request.FILES or None)
    formset = IngredientModelFormset(queryset=Ingredient.objects.none())
    formset_procedure = ProcedureModelFormset(queryset=Procedure.objects.none())
elif request.method == 'POST':
    form = RecipeForm(request.POST, request.FILES or None)
    formset = IngredientModelFormset(request.POST, request.FILES or None)
    formset_procedure = ProcedureModelFormset(request.POST, request.FILES or None)
    if form.is_valid() and formset.is_valid() and formset_procedure.is_valid():
        recipe = form.save()
        for forms in formset:
            ingredient = forms.save(commit=False)
            ingredient.recipe = recipe
            ingredient.save()
        for fp in formset_procedure:
            procedure = fp.save(commit=False)
            procedure.recipe = recipe
            procedure.save()
        return redirect(recipe.get_absolute_url())
context = {
    "form": form,
    'formset': formset,
    'formset_procedure': formset_procedure,
}
return render(request, "recipes/recipe_form.html", context)

更好:

fun String.inAscending(): String = toMutableList().sortedBy { it }.joinToString("")

答案 4 :(得分:0)

我认为,以 kotlin 的方式进行操作,即

<script type="text/javascript">
var _fV4UI=true;var _spPageContextInfo = webLanguage: 1033, currentLanguage: 1033, webUIVersion:4,pageListId:"{8faf05f2-b852-44b4-8a46-c7ee47b76e0a}",pageItemId:375,userId:24161, alertsEnabled:false, siteServerRelativeUrl: "\u002fsites\u002fcontent", allowSilverlightPrompt:'True'};//]]>
</script>