字符串的大写
让我们想象一下,我们有一个简单的抽象输入形式,其目的是接受某个字符串,该字符串可以包含任何字符。
string = "mystical characters"
我们需要通过将第一个字符变为大写来处理该字符串。是的,这是我们的主要目标。此后,我们需要在一些抽象视图模板中显示这个转换后的字符串。所以,问题是:我们真的需要检查第一个字符是否已经正确写入(大写)或者我们可以只写这个吗?
theresult = string.capitalize
=> "Mystical characters"
哪种方法更好:检查然后大写(如果需要)或强制大写?
Let us imagine, that we have a simple abstract input form, whose aim is accepting some string, which could consist of any characters.
string = "mystical characters"
We need to process this string by making first character uppercased. Yes, that is our main goal. Thereafter we need to display this converted string in some abstract view template. So, the question is: do we really need to check whether the first character is already written correctly (uppercased) or we are able to write just this?
theresult = string.capitalize
=> "Mystical characters"
Which approach is better: check and then capitalize (if need) or force capitalization?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
首先检查是否需要处理某些内容,因为 String#capitalize不仅将第一个字符转换为大写,还将所有其他字符转换为小写。所以..
这可能不是想要的结果。
Check first if you need to process something, because String#capitalize doesn't only convert the first character to uppercase, but it also converts all other characters downcase. So..
That might not be the wanted result.
如果我理解正确的话,无论如何你都会将字符串大写,那么为什么还要检查它是否已经大写呢?
If I understood correctly you are going to capitalize the string anyway, so why bother checking if it's already capitalized?
基于 Tonttu 答案 我建议不要太担心,只需大写如下:
Based on Tonttu answer I would suggest not to worry too much and just capitalize like this:
我在导入一堆名称时遇到了 Tonttu 的问题,我选择了:
编辑:(一年多)之后不可避免的重构。
虽然绝对不易于阅读,但它在声明较少的临时变量时获得相同的结果。
I ran in to Tonttu's problem importing a bunch of names, I went with:
EDIT: The inevitable refactor (over a year) later.
while definitely not easier to read, it gets the same result while declaring fewer temporary variables.
我想你可以写这样的话:
就我个人而言,我会这样做
I guess you could write something like:
Personally I would just do
除非你为大写字符串设置了一个标志,你要检查它而不是只大写而不检查。
此外,大写本身可能正在执行一些检查。
Unless you have a flag to be set for capitalized strings which you going to check than just capitalize without checking.
Also the capitalization itself is probably performing some checking.