Go语言modifyUp函数处理(up,n)格式字符串失效问题求助
问题修复方案
原代码的核心问题
- 条件判断不匹配:代码只检查单词后缀是否为
"(up)",但输入里的标记是"(up, 2)",导致触发逻辑根本没执行 - 单词数量计算错误:默认
numWords=1再加上numbers,比如n=2时会算成3,完全不符合需求 - 转换范围逻辑混乱:循环包含了标记词本身,而且起始位置计算错误
- 未移除标记词:预期输出里没有
"(up,2)",但原代码保留了这个部分
修正后的代码
import ( "strings" "strconv" "fmt" ) // modifyUp converts specified number of words before (up, n) to uppercase func modifyUp(line string) string { words := strings.Fields(line) // 倒序遍历,避免修改数组后影响索引 for i := len(words) - 1; i >= 0; i-- { word := words[i] // 检查是否包含(up相关格式 if strings.Contains(word, "(up") { var numWords int // 处理两种格式:(up) 和 (up, n) if strings.HasSuffix(word, "(up)") { numWords = 1 // 移除(up)后缀 words[i] = strings.TrimSuffix(word, "(up)") } else if strings.HasSuffix(word, ")") && strings.Contains(word, "(up, ") { // 提取数字部分 numStr := strings.TrimSuffix(strings.Split(word, ", ")[1], ")") num, err := strconv.Atoi(numStr) if err != nil { // 数字解析失败,默认处理1个单词 numWords = 1 } else { numWords = num } // 移除(up, n)后缀 words[i] = strings.TrimSuffix(word, fmt.Sprintf("(up, %d)", numWords)) } else { // 不符合格式,跳过 continue } // 计算要转换的单词起始索引 startIdx := i - numWords if startIdx < 0 { startIdx = 0 } // 转换前面numWords个单词为大写 for j := startIdx; j < i; j++ { words[j] = strings.ToUpper(words[j]) } // 如果处理后的单词为空(比如原单词就是"(up,2)"),则移除该位置 if words[i] == "" { words = append(words[:i], words[i+1:]...) } } } return strings.Join(words, " ") }
关键修改点说明
- 倒序遍历:避免修改单词数组后,后续索引偏移导致错误
- 格式匹配优化:同时支持
(up)和(up, n)两种格式,不再局限于固定后缀 - 正确计算转换范围:转换的是标记词前面的
numWords个单词(startIdx到i-1),不包含标记词本身 - 移除无效标记词:如果标记词本身没有实际内容(比如单独的"(up,2)"),直接从数组中删除
- 错误处理:数字解析失败时默认处理1个单词,增强鲁棒性
测试验证
输入:"This is so exciting (up, 2)"
输出:"This is SO EXCITING",符合预期
内容的提问来源于stack exchange,提问作者Moussa Fall
相关产品推荐
相关产品推荐

