gpt4 book ai didi

string - 如何在 Swift 的条件语句中比较大小写字母

转载 作者:行者123 更新时间:2023-11-28 06:56:54 26 4
gpt4 key购买 nike

如果这是重复的,我们深表歉意。我有一个名为 inputString() 的辅助函数,它接受用户输入并返回一个字符串。我想根据输入的是大写字符还是小写字符来继续。这是我的代码:

 print("What do you want to do today? Enter 'D' for Deposit or 'W' for Withdrawl.")

operation = inputString()

if operation == "D" || operation == "d" {

print("Enter the amount to deposit.")

我的程序在第一个打印函数后退出,但没有给出编译器错误。我不知道我做错了什么。

最佳答案

重要的是要记住有 a whole slew of purely whitespace characters出现在字符串中,有时,这些空白字符会导致像这样的问题。

因此,无论何时您确定两个字符串应该相等,在它们的两端打印某种非空白字符会很有用。

例如:

print("Your input was <\(operation)>")

这应该在输入的两边打印带有尖括号的用户输入。

如果你将那行代码插入到你的程序中,你会看到它打印出如下内容:

Your input was <D
>

事实证明,您的 inputString() 方法正在捕获用户按下以提交输入的换行符 (\n)。您应该改进您的 inputString() 方法以继续并在返回其值之前修剪该换行符。


我觉得在这里提一下您的 inputString 方法非常笨拙并且需要导入模块非常重要。但是有一种更简单的纯 Swift 方法:readLine()

Swift 的 readLine() 方法做的正是您的 inputString() 方法应该做的,默认情况下,它会为您去除末尾的换行符(您可以传递一个可选参数以防止该方法去除换行符)。

我的代码版本如下所示:

func fetchInput(prompt: String? = nil) -> String? {
if let prompt = prompt {
print(prompt, terminator: "")
}
return readLine()
}

if let input = fetchInput("Enter some input: ") {
if input == "X" {
print("it matches X")
}
}

关于string - 如何在 Swift 的条件语句中比较大小写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33271129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com