从字符串中获取单个单词可以通过以下几种方法实现:
string = "Hello world"
words = string.split()
print(words) # 输出:['Hello', 'world']
var string = "Hello world";
var words = string.match(/\b\w+\b/g);
console.log(words); // 输出:['Hello', 'world']
String string = "Hello world";
List<String> words = new ArrayList<>();
String word = "";
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (Character.isLetterOrDigit(c)) {
word += c;
} else if (!word.isEmpty()) {
words.add(word);
word = "";
}
}
if (!word.isEmpty()) {
words.add(word);
}
System.out.println(words); // 输出:['Hello', 'world']
以上是从字符串中获取单个单词的几种常见方法。根据具体的编程语言和场景,选择合适的方法来实现。
领取专属 10元无门槛券
手把手带您无忧上云