如何在Emacs中将英文字符串转换为大写

6
我想知道人们在正确地大写英文字符串时使用的方法,因为“capitalize”不能完成这项工作:
(capitalize "can't")
=> "Can'T"

虽然编写这个函数很简单,但我想知道是否有首选的内置方法来完成它。
4个回答

8
也许您可以暂时将'添加到当前单词成分语法表中:
(modify-syntax-entry ?' "w")

(capitalize "can't")
=> "Can't"

2
+1,但是要注意一点: (将“this is a 'test'”首字母大写) “This Is A 'test'” - cobbal

5

我将M-c按键绑定为capitalize-word,它可以正确地将can't大写。


capitalize-word 能够正常工作是因为它将 "can't" 视为两个单词 can 和 t。这就是为什么最初使用字符串而不是单词。使用 capitalize-word,我必须循环遍历字符串中的所有单词,并且它会将 "t" 大写。 - Federico Builes
1
不对,capitalize-word将can't视为单词,不会大写字母t。但它是一个交互式函数,可将当前缓冲区中的下一个单词(或N个单词)大写。它不适用于传递的字符串。所以无论如何都不能用于你。 - Cheeso
我也曾这样想,但如果你在“can't”上运行“M-2 M-x capitalize-word”,你会得到“Can'T”。因此,它将“can't”视为两个单词。 - seth
1
刚刚做了两次。在文本文件中,它按照我描述的方式工作,将 "can't" 视为一个单词。当单词 "can't" 出现在 C# 文件内的注释中时,它按照所描述的方式工作,将 "can't" 视为两个单词。 - Cheeso

1

目前的答案很好,但如果您在代码中使用字符串,可以使用s字符串操作库。s-capitalize将句子中的第一个单词大写。

ELISP> (s-capitalize "can't win the war on drugs in a prison, where the hell you gonna win it?")
"Can't win the war on drugs in a prison, where the hell you gonna win it?"
ELISP> (s-join " " (-map 's-capitalize (s-split " " "can't win the war on drugs in a prison, where the hell you gonna win it?")))
"Can't Win The War On Drugs In A Prison, Where The Hell You Gonna Win It?"

s-titleize函数可以将字符串中的每个单词首字母大写,但它只是对内置的capitalize方法的简单封装,因此需要使用Karl Voigtland的解决方案

ELISP> (s-titleize "Girl, you can't even think of calling this shit a war.")
"Girl, You Can'T Even Think Of Calling This Shit A War."
ELISP> (progn (modify-syntax-entry ?' "w") (s-titleize "Girl, you can't even think of calling this shit a war."))
"Girl, You Can't Even Think Of Calling This Shit A War."

1
当然,行为取决于所使用的语法表,即取决于主模式。如果'字符具有"w p"语法,则应该正常工作。这在文本模式下是成立的,但在大多数编程模式下并非如此。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接