使用 JS、Python 和 Java 8 学习算法:句子首字母大写
1:使用内置库的简洁解决方案
2:使用循环的暴力解法
由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!
距离我上次发文章已经有一段时间了。今天这篇文章内容简单易懂,是关于康复的。
本系列文章以 Stephen Grider在Udemy 上的课程为基础,涵盖三种不同的编程语言。JavaScript 的解决方案由 Stephen 提供,我尝试将其“翻译”成 Python 和 Java 代码。
今天的问题是什么?
--- 说明:
编写一个函数,该函数接受一个字符串作为参数。函数应将
字符串中每个单词的首字母大写,然后
返回大写后的字符串。---
示例:
capitalize('a short sentence') --> 'A Short Sentence'
capitalize('a lazy fox') --> 'A Lazy Fox'
capitalize('look, it is working!') --> 'Look, It Is Working!'
1:使用内置库的简洁解决方案
JavaScript:
function capitalize(sentence) {
const words = [];
for (let word of sentence.split(' ')) {
words.push(word[0].toUpperCase() + word.slice(1));
}
return words.join(' ');
}
Python:
def capitalize1(sentence: str) -> str:
words = [word[0].upper() + word[1:] for word in sentence.split()]
return ' '.join(words)
def capitalize2(sentence: str) -> str:
return ' '.join([word.capitalize() for word in sentence.split()])
def capitalize3(sentence: str) -> str:
return sentence.title()
Java:
import java.util.LinkedList;
import java.util.List;
public static String capitalize(String sentence) {
List<String> words = new LinkedList<>();
for (String word : sentence.split(" ")) {
words.add(String.valueOf(word.charAt(0)).toUpperCase() + word.substring(1));
}
return String.join(" ", words);
}
2:使用循环的暴力解法
JavaScript:
function capitalize(sentence) {
let result = sentence[0].toUpperCase();
for (let i = 1; i < sentence.length; i++) {
if (sentence[i - 1] === ' ') {
result += sentence[i].toUpperCase();
} else {
result += sentence[i];
}
}
return result;
}
Python:
def capitalize(sentence: str) -> str:
result = ''
for i, char in enumerate(sentence):
if i == 0 or sentence[i - 1] == ' ':
result += char.upper()
else:
result += char
return result
Java:
public static String capitalize(String sentence) {
StringBuilder result = new StringBuilder(String.valueOf(sentence.charAt(0)).toUpperCase());
for (int i = 1; i < sentence.length(); i++) {
if (sentence.charAt(i - 1) == ' ') {
result.append(String.valueOf(sentence.charAt(i)).toUpperCase());
} else {
result.append(sentence.charAt(i));
}
}
return result.toString();
}
感谢您阅读至此。希望很快能再次见到您!
文章来源:https://dev.to/tommy3/learning-algorithms-with-js-python-and-java-8-sentence-capitalization-1ld7