---
tags:
    - "String"
    - "Words"
    - "Amount"
    - "Count"
    - "Space"
---

# Word Count

[Strings](index.md) / **Word Count**

<div class="grid cards" markdown>

* :green_circle: Can Read

* :red_circle: Cannot Write

</div>

## Description

How many words a text has, understanding a word as a run of non whitespace characters

## Parameters

| Name | Description |
| :--- | :---------- |
| Text | The text whose words are counted |

## Code

```cs
using System;
using UnityEngine;
using VisualScript.Icons;

namespace VisualScript.Runtime
{
    [Get]

    [Title("Word Count")]
    [Category("Strings/Word Count")]

    [Description("How many words a text has, understanding a word as a run of non whitespace characters")]
    [Image(typeof(IconTally), ColorTheme.Type.Yellow, typeof(BadgeString))]

    [Parameter("Text", "The text whose words are counted")]

    [Keywords("String", "Words", "Amount", "Count", "Space")]

    [Serializable]
    public class TypeNumberStringWordCount : TypeNumber
    {
        [SerializeField] private GetString m_Text = new GetString();

        public override double GetPreview(GameObject source) => WordCount(this.m_Text.GetPreview(source));

        public override double Get(Args args) => WordCount(this.m_Text.Get(args));

        private static double WordCount(string text)
        {
            if (string.IsNullOrEmpty(text)) return 0;

            int count = 0;
            bool insideWord = false;

            foreach (char character in text)
            {
                if (char.IsWhiteSpace(character))
                {
                    insideWord = false;
                    continue;
                }

                if (!insideWord) count += 1;
                insideWord = true;
            }

            return count;
        }

        public override string ToString()
        {
            return $"Words in {this.m_Text}";
        }

        protected override SubscriptionMode Subscription => SubscriptionMode.OnChange;
    }
}

```

