瀏覽代碼

LibGUI: Add number_of_words() to TextEditors

Returns the total number of words in a document.
thankyouverycool 3 年之前
父節點
當前提交
46043b71cb
共有 2 個文件被更改,包括 24 次插入0 次删除
  1. 23 0
      Userland/Libraries/LibGUI/TextEditor.cpp
  2. 1 0
      Userland/Libraries/LibGUI/TextEditor.h

+ 23 - 0
Userland/Libraries/LibGUI/TextEditor.cpp

@@ -1335,6 +1335,29 @@ size_t TextEditor::number_of_selected_words() const
     return word_count;
 }
 
+size_t TextEditor::number_of_words() const
+{
+    if (document().is_empty())
+        return 0;
+
+    size_t word_count = 0;
+    bool in_word = false;
+    auto text = this->text();
+    for (char c : text) {
+        if (in_word && is_ascii_space(c)) {
+            in_word = false;
+            word_count++;
+            continue;
+        }
+        if (!in_word && !is_ascii_space(c))
+            in_word = true;
+    }
+    if (in_word)
+        word_count++;
+
+    return word_count;
+}
+
 void TextEditor::delete_selection()
 {
     auto selection = normalized_selection();

+ 1 - 0
Userland/Libraries/LibGUI/TextEditor.h

@@ -126,6 +126,7 @@ public:
     bool write_to_file_and_close(int fd);
     bool has_selection() const { return m_selection.is_valid(); }
     String selected_text() const;
+    size_t number_of_words() const;
     size_t number_of_selected_words() const;
     void set_selection(TextRange const&);
     void clear_selection();