检测特定字符串



最近,我有一个学校的项目,让我挣扎了一个星期。我真的需要帮助。

我的程序接受一个字符串输入,并将其修改为返回另一个大写或小写版本的字符串,到目前为止它是有效的。但是当我输入:这太令人兴奋了(向上,2)&;输出保持不变,当它应该是&;This is SO exciting &;我的观点是能够处理这种情况:(up, n),知道后面跟着"(up)"必须大写。如下图所示:

提前感谢!

// modifyUp converts words before (up) to uppercase
func modifyUp(line string) string {
words := strings.Fields(line)
var numWords int
var numbers int
for i, word := range words {
if strings.HasSuffix(word, "(up)") && i > 0 {
// Convert word(s) to uppercase
numWords = 1
if strings.Contains(word, ",") {
// Handle comma-separated words
numbers, _ = strconv.Atoi(strings.TrimSuffix(strings.Split(word, ",")[1], ")"))
word = strings.TrimSuffix(word, fmt.Sprintf(",%d)", numbers))
numWords += numbers
} else {
word = strings.TrimSuffix(word, "(up)")
}
// Convert preceding word(s) to uppercase
for j := i - numWords + 1; j <= i; j++ {
if j >= 0 {
words[j] = strings.ToUpper(words[j])
}
}
// Replace modified word with original word
words[i-numWords+1] = word
}
}
return strings.Join(words, " ")

正如评论中提到的,您正在检查(up),而(up, 2)不会检测到。检查这一点的一个简单方法是,您可以在for循环开始时抛出一个fmt.Println(word)来验证您正在检查的每个单词。对于This is so exciting (up, 2),您得到

This
is
so
exciting
(up,
2)

可以看到,找到了(up,而不是(up)。最重要的是,2)与check分开。

如果我们保持相同的逻辑,你现在有,一个快速修复如下:

func modifyUp(line string) string {
words := strings.Fields(line)
var numWords int
for i, word := range words {
if (strings.HasSuffix(word, "(up)") || strings.HasSuffix(word, "(up,")) && i > 0 {
// Convert word(s) to uppercase
numWords = 1
if strings.Contains(word, ",") {
var numbers int
// Handle comma-separated words
numbers, _ = strconv.Atoi(strings.TrimRight(words[i+1], ")"))
words[i] = ""
words[i+1] = ""
numWords = numbers
} else {
words[i] = ""
}
// Convert preceding word(s) to uppercase
for j := i - numWords; j <= i; j++ {
words[j] = strings.ToUpper(words[j])
}
}
}
return strings.Join(words, " ")
}

我对代码做了一些额外的更改,以便在正确解析后使其工作。你也可以删除words[i-numWords+1] = word,因为你已经在转换中替换了它。

希望这对你有帮助,如果你有任何后续的问题,请告诉我。

我终于找到了另一种方法

func modifyUp(line string) string {
words := strings.Fields(line)
//var numWords int
var numbers int
for i, word := range words {
if word == "(up," && i < len(words)-1 {
ok := splitWord(words[i+1])
if ok {
wr := words[i+1]
numbers, _ = strconv.Atoi(wr[:len(wr)-1])
words[i], words[i+1] = "", ""
for j := i - 1; j >= 0; j-- {
if numbers == 0 {
break
} else {
words[j] = strings.ToUpper(words[j])
numbers--
}
}
}
break
}
if word == "(up)" && i > 0 {
words[i-1] = strings.ToUpper(words[i-1])
words[i] = ""
}
}
return strings.Join(words, " ")
}

感谢大家的贡献

相关内容

  • 没有找到相关文章

最新更新