如何找出两个字符串的差异词?Jetpack Compose实现求助
解决字符串差异词提取与展示问题
你的代码存在几个问题导致无法实现需求:
- 仅遍历旧单词列表的索引,若新旧单词数量不一致会直接抛出越界异常
- 只输出了新字符串中的差异词,完全没处理旧字符串里的对应差异
- 找到第一个差异就终止循环,无法处理多组差异的情况
下面是修正后的代码,能正确提取并展示新旧字符串中的差异词:
@Composable fun DifferenceText(oldText: String, currentText: String) { val oldWords = oldText.split(" ") val currentWords = currentText.split(" ") val maxSize = maxOf(oldWords.size, currentWords.size) val differences = mutableListOf<Pair<String?, String?>>() // 遍历所有可能的位置,收集差异 for (i in 0 until maxSize) { val oldWord = if (i < oldWords.size) oldWords[i] else null val currentWord = if (i < currentWords.size) currentWords[i] else null if (oldWord != currentWord) { differences.add(oldWord to currentWord) } } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { if (differences.isEmpty()) { Text(text = "两个字符串完全一致") } else { differences.forEach { (old, current) -> if (old != null) { Text(text = "旧字符串差异词: *$old*", style = TextStyle(color = Color.Red)) } if (current != null) { Text(text = "新字符串差异词: *$current*", style = TextStyle(color = Color.Green)) } Spacer(modifier = Modifier.height(8.dp)) } } } }
关键改进点:
- 处理了新旧单词列表长度不一致的情况,避免索引越界
- 收集所有位置的差异,支持多组差异词展示
- 分别提取并标记旧字符串和新字符串中的差异词,用颜色区分更直观
- 增加了无差异时的提示文本
比如你给出的示例输入:
DifferenceText(oldText = "Nature is so beautiful", currentText = "Nature is very beautiful")
会输出:
旧字符串差异词: so
新字符串差异词: very
内容的提问来源于stack exchange,提问作者Saurabh Jain
相关产品推荐
相关产品推荐

