Count Occurrences#
Strings / Count Occurrences
Can Read
Cannot Write
Description#
How many times a text is found inside another one, without overlapping
Parameters#
| Name | Description |
|---|---|
| Text | The text where the occurrences are searched |
| Find | The text that is searched for |
| Ignore Case | Whether upper and lower case characters are considered the same |
Code#
using System;
using UnityEngine;
using VisualScript.Icons;
namespace VisualScript.Runtime
{
[Get]
[Title("Count Occurrences")]
[Category("Strings/Count Occurrences")]
[Description("How many times a text is found inside another one, without overlapping")]
[Image(typeof(IconTally), ColorTheme.Type.Yellow, typeof(BadgeMagnifier))]
[Parameter("Text", "The text where the occurrences are searched")]
[Parameter("Find", "The text that is searched for")]
[Parameter("Ignore Case", "Whether upper and lower case characters are considered the same")]
[Keywords("String", "Amount", "Times", "Repetitions", "Find", "Search")]
[Serializable]
public class TypeNumberStringCountOccurrences : TypeNumber
{
[SerializeField] private GetString m_Text = new GetString();
[SerializeField] private GetString m_Find = new GetString();
[SerializeField] private GetBool m_IgnoreCase = new GetBool(false);
public override double GetPreview(GameObject source) => Count(
this.m_Text.GetPreview(source),
this.m_Find.GetPreview(source),
this.m_IgnoreCase.GetPreview(source)
);
public override double Get(Args args) => Count(
this.m_Text.Get(args),
this.m_Find.Get(args),
this.m_IgnoreCase.Get(args)
);
private static double Count(string text, string find, bool ignoreCase)
{
if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(find)) return 0;
StringComparison comparison = ignoreCase
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
int count = 0;
int index = text.IndexOf(find, comparison);
while (index >= 0)
{
count += 1;
index = text.IndexOf(find, index + find.Length, comparison);
}
return count;
}
public override string ToString()
{
return $"Count {this.m_Find} in {this.m_Text}";
}
protected override SubscriptionMode Subscription => SubscriptionMode.OnChange;
}
}