Kotlin替换字符串中的多个单词

时间:2018-05-22 23:40:29

标签: kotlin

如何使用.replace()

在Kotlin中用其他内容替换字符串的许多部分

例如,我们只能通过替换一个单词

来实现
fun main(args: Array<String>) {

    var w_text = "welcome his name is John"

    println("${w_text.replace("his","here")}")
}

结果将是&#34;欢迎来到此名称是John&#34;

最后我们需要的结果是&#34;欢迎来到这里,名字是alles&#34;

他的替换为此处,将约翰替换为 alles ,使用.replace()

6 个答案:

答案 0 :(得分:4)

如果您有许多替换规则,那么创建它们的映射并在循环中调用replace方法:

val map = mapOf("his" to "here", "john" to "alles", ...)
val sentence = "welcome his name is John"
var result = sentence
map.forEach { t, u -> result = result.replace(t, u) }
println(result)

答案 1 :(得分:3)

您可以使用多个import operator a = [10, 16, 29, 1, 4, 5, 7, 9, 13, 15] d = {k:v for k, v in enumerate(a)} sorted_d = sorted(d.items(), key=operator.itemgetter(1), reverse=True) result_list = [k[0] for k in sorted_d][:3] print(result_list) # [2, 1, 9] 的连续调用来执行此操作:

replace()

答案 2 :(得分:3)

您可以编写一个重载String::replace

的扩展程序
fun String.replace(vararg replacements: Pair<String, String>): String {
    var result = this
    replacements.forEach { (l, r) -> result = result.replace(l, r) }
    return result
}


fun main(args: Array<String>) {
    val sentence = "welcome his name is John"
    sentence.replace("his" to "here", "John" to "alles")
}

答案 3 :(得分:0)

这是一个班轮:

    public static void main(String... args) {
        testBasic();
        testAsync();
    }
    private static void testBasic() {
        out.println("*****************************************");
        out.println("********** TESTING thenCompose **********");
        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletableFuture[] futures = Stream.iterate(0, i -> i+1)
                .limit(3)
                .map(i -> CompletableFuture.supplyAsync(() -> runStage1(i), executorService))
                .map(future -> future.thenCompose(i -> CompletableFuture.supplyAsync(() -> runStage2(i), executorService)))
                .map(f -> f.thenAccept(out::println))
                .toArray(size -> new CompletableFuture[size]);
        CompletableFuture.allOf(futures).join();
    }

    private static void testAsync() {
        out.println("*****************************************");
        out.println("******* TESTING thenComposeAsync ********");
        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletableFuture[] futures = Stream.iterate(0, i -> i+1)
                .limit(3)
                .map(i -> CompletableFuture.supplyAsync(() -> runStage1(i), executorService))
                .map(future -> future.thenComposeAsync(i ->
                        CompletableFuture.supplyAsync(() -> runStage2(i), executorService)))
                .map(f -> f.thenAccept(out::println))
                .toArray(size -> new CompletableFuture[size]);
        CompletableFuture.allOf(futures).join();
    }

    private static Integer runStage1(int a) {
        String s = String.format("Start: stage - 1 - value: %d - thread name: %s",
                a, Thread.currentThread().getName());
        out.println(s);
        Long start = System.currentTimeMillis();
        try {
            Thread.sleep(1500 + Math.abs(new Random().nextInt()) % 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        s = String.format("Finish: stage - 1 - value: %d - thread name: %s - time cost: %d",
                a, Thread.currentThread().getName(), (System.currentTimeMillis() - start));
        out.println(s);
        return Integer.valueOf(a % 3);
    }

    private static Integer runStage2(int b) {
        String s = String.format("Start: stage - 2 - value: %d - thread name: %s",
                b, Thread.currentThread().getName());
        out.println(s);
        Long start = System.currentTimeMillis();
        try {
            Thread.sleep(200 + Math.abs(new Random().nextInt()) % 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        s = String.format("Finish: stage - 2 - value: %d - thread name: %s - time cost: %d",
                b, Thread.currentThread().getName(), (System.currentTimeMillis() - start));
        out.println(s);
        return Integer.valueOf(b);
    }

测试:

*****************************************
********** TESTING thenCompose **********
Start: stage - 1 - value: 1 - thread name: pool-1-thread-2
Start: stage - 1 - value: 0 - thread name: pool-1-thread-1
Start: stage - 1 - value: 2 - thread name: pool-1-thread-3
Finish: stage - 1 - value: 1 - thread name: pool-1-thread-2 - time cost: 1571
Start: stage - 2 - value: 1 - thread name: pool-1-thread-4  // using a new thread?????
Finish: stage - 1 - value: 2 - thread name: pool-1-thread-3 - time cost: 1875
Start: stage - 2 - value: 2 - thread name: pool-1-thread-2
Finish: stage - 1 - value: 0 - thread name: pool-1-thread-1 - time cost: 2198
Start: stage - 2 - value: 0 - thread name: pool-1-thread-3
Finish: stage - 2 - value: 2 - thread name: pool-1-thread-2 - time cost: 442
2
Finish: stage - 2 - value: 1 - thread name: pool-1-thread-4 - time cost: 779
1
Finish: stage - 2 - value: 0 - thread name: pool-1-thread-3 - time cost: 1157
0
*****************************************
******* TESTING thenComposeAsync ********
Start: stage - 1 - value: 0 - thread name: pool-2-thread-1 // all in same thread
Start: stage - 1 - value: 1 - thread name: pool-2-thread-2
Start: stage - 1 - value: 2 - thread name: pool-2-thread-3
Finish: stage - 1 - value: 0 - thread name: pool-2-thread-1 - time cost: 1623
Start: stage - 2 - value: 0 - thread name: pool-2-thread-1
Finish: stage - 1 - value: 1 - thread name: pool-2-thread-2 - time cost: 1921
Start: stage - 2 - value: 1 - thread name: pool-2-thread-2
Finish: stage - 1 - value: 2 - thread name: pool-2-thread-3 - time cost: 1932
Start: stage - 2 - value: 2 - thread name: pool-2-thread-3
Finish: stage - 2 - value: 0 - thread name: pool-2-thread-1 - time cost: 950
0
Finish: stage - 2 - value: 2 - thread name: pool-2-thread-3 - time cost: 678
2
Finish: stage - 2 - value: 1 - thread name: pool-2-thread-2 - time cost: 956
1

答案 4 :(得分:0)

对于那些希望替换文本中的值映射的人:

private fun replaceText(text: String, keys: Map<String, String>): String =
    val replaced = map.entries.fold(text) { acc, (key, value) -> acc.replace(key, value) }

答案 5 :(得分:0)

仅使用replace而没有任何正则表达式的问题是: 假设我想用字符串“我的包在哪里?你的包在这里”中的“这里”替换“这里”的出现。可以想象,结果将是“我的包在那里?你的包在那里。”这是不正确的。解决方案是使用如下所示的正则表达式。

    var str = "Where is my bag? Your bag is here."
    val replacements = setOf("\\bhere\\b" to "there",
        "\\bjohn\\b" to "alles")
    replacements.forEach {
        str = str.replace(Regex(it.first), it.second)
    }
相关问题