Skip to content

Commit

Permalink
Optimize string finder.
Browse files Browse the repository at this point in the history
  • Loading branch information
kingcean committed Jul 20, 2023
1 parent 9469050 commit 214df3d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
37 changes: 37 additions & 0 deletions Core/Text/Utils/StringFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ public StringFinder(string s)
Value = Previous = string.Empty;
}

/// <summary>
/// Initializes a new instance of the StringFinder class.
/// </summary>
/// <param name="s">The source string.</param>
public StringFinder(StringBuilder s)
: this(s?.ToString())
{
}

/// <summary>
/// Gets the source string.
/// </summary>
Expand Down Expand Up @@ -85,6 +94,34 @@ public StringFinder(string s)
/// </summary>
public int RestLength => Rest.Length;

/// <summary>
/// Gets the sub-string before a search string.
/// </summary>
/// <param name="q">The search string.</param>
/// <param name="offset">The zero-based offset.</param>
/// <returns>The sub-string.</returns>
public string PreviewBefore(string q, out int offset)
{
if (string.IsNullOrEmpty(q))
{
offset = Offset;
return string.Empty;
}

var s = Rest;
var index = s.IndexOf(q);
if (index < 0)
{
Value = string.Empty;
offset = Source.Length;
return string.Empty;
}

var value = Rest.Substring(0, index);
offset = Offset + index;
return value;
}

/// <summary>
/// Gets the sub-string before a search string. The search string is in the rest string.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions UnitTest/Text/StringUnitTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public void TestStringFinder()
"."
});
Assert.IsFalse(finder.IsEnd);
Assert.AreEqual(TestString.Length - 1, finder.Offset);
Assert.AreEqual("\"", finder.Before(1));
Assert.AreEqual("\"", finder.Value);
Assert.IsTrue(finder.IsEnd);
Expand Down

0 comments on commit 214df3d

Please sign in to comment.