SubtitleEdit/libse/StringExtensions.cs

439 lines
14 KiB
C#
Raw Normal View History

2016-02-08 21:11:03 +01:00
using System;
using System.Collections.Generic;
2016-02-08 21:11:03 +01:00
using System.Globalization;
using System.Text;
namespace Nikse.SubtitleEdit.Core
{
public static class StringExtensions
{
public static bool LineStartsWithHtmlTag(this string text, bool threeLengthTag, bool includeFont = false)
{
if (text == null || (!threeLengthTag && !includeFont))
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
return false;
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
return StartsWithHtmlTag(text, threeLengthTag, includeFont);
}
public static bool LineEndsWithHtmlTag(this string text, bool threeLengthTag, bool includeFont = false)
{
if (text == null)
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
return false;
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
var len = text.Length;
if (len < 6 || text[len - 1] != '>')
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
return false;
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
// </font> </i>
if (threeLengthTag && len > 3 && text[len - 4] == '<' && text[len - 3] == '/')
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
return true;
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
if (includeFont && len > 8 && text[len - 7] == '<' && text[len - 6] == '/')
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
return true;
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
return false;
}
public static bool LineBreakStartsWithHtmlTag(this string text, bool threeLengthTag, bool includeFont = false)
{
if (text == null || (!threeLengthTag && !includeFont))
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
return false;
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
var newLineIdx = text.IndexOf(Environment.NewLine, StringComparison.Ordinal);
if (newLineIdx < 0 || text.Length < newLineIdx + 5)
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
return false;
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
text = text.Substring(newLineIdx + 2);
return StartsWithHtmlTag(text, threeLengthTag, includeFont);
}
private static bool StartsWithHtmlTag(string text, bool threeLengthTag, bool includeFont)
{
if (threeLengthTag && text.Length >= 3 && text[0] == '<' && text[2] == '>' && (text[1] == 'i' || text[1] == 'I' || text[1] == 'u' || text[1] == 'U' || text[1] == 'b' || text[1] == 'B'))
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
return true;
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
if (includeFont && text.Length > 5 && text.StartsWith("<font", StringComparison.OrdinalIgnoreCase))
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
return text.IndexOf('>', 5) >= 5; // <font> or <font color="#000000">
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
return false;
}
public static bool StartsWith(this string s, char c)
{
return s.Length > 0 && s[0] == c;
}
public static bool StartsWith(this StringBuilder sb, char c)
{
return sb.Length > 0 && sb[0] == c;
}
public static bool EndsWith(this string s, char c)
{
return s.Length > 0 && s[s.Length - 1] == c;
}
public static bool EndsWith(this StringBuilder sb, char c)
{
return sb.Length > 0 && sb[sb.Length - 1] == c;
}
public static bool Contains(this string source, char value)
{
return source.IndexOf(value) >= 0;
}
public static bool Contains(this string source, char[] value)
{
return source.IndexOfAny(value) >= 0;
}
public static bool Contains(this string source, string value, StringComparison comparisonType)
{
return source.IndexOf(value, comparisonType) >= 0;
}
public static List<string> SplitToLines(this string s)
2016-02-08 21:11:03 +01:00
{
//original non-optimized version: return source.Replace("\r\r\n", "\n").Replace("\r\n", "\n").Replace('\r', '\n').Replace('\u2028', '\n').Split('\n');
var lines = new List<string>();
int start = 0;
int max = s.Length;
int i = 0;
while (i < max)
{
var ch = s[i];
if (ch == '\r')
{
if (i < s.Length - 2 && s[i + 1] == '\r' && s[i + 2] == '\n') // \r\r\n
{
lines.Add(start < i ? s.Substring(start, i - start) : string.Empty);
i += 3;
start = i;
continue;
}
if (i < s.Length - 1 && s[i + 1] == '\n') // \r\n
{
lines.Add(start < i ? s.Substring(start, i - start) : string.Empty);
i += 2;
start = i;
continue;
}
lines.Add(start < i ? s.Substring(start, i - start) : string.Empty);
i++;
start = i;
continue;
}
if (ch == '\n' || ch == '\u2028')
{
lines.Add(start < i ? s.Substring(start, i - start) : string.Empty);
i++;
start = i;
continue;
}
i++;
}
lines.Add(start < i ? s.Substring(start, i - start) : string.Empty);
return lines;
2016-02-08 21:11:03 +01:00
}
public static int CountWords(this string source)
{
return HtmlUtil.RemoveHtmlTags(source, true).Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
2016-02-08 21:11:03 +01:00
// http://www.codeproject.com/Articles/43726/Optimizing-string-operations-in-C
public static int FastIndexOf(this string source, string pattern)
{
2019-01-29 21:33:20 +01:00
if (string.IsNullOrEmpty(pattern))
2019-01-19 14:40:37 +01:00
{
2019-01-29 21:33:20 +01:00
return -1;
2019-01-19 14:40:37 +01:00
}
2019-01-29 21:33:20 +01:00
char c0 = pattern[0];
2019-01-19 14:40:37 +01:00
if (pattern.Length == 1)
{
2019-01-29 21:33:20 +01:00
return source.IndexOf(c0);
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
int limit = source.Length - pattern.Length + 1;
2019-01-19 14:40:37 +01:00
if (limit < 1)
{
return -1;
}
2019-01-29 21:33:20 +01:00
2016-02-08 21:11:03 +01:00
char c1 = pattern[1];
2019-01-29 21:33:20 +01:00
2016-02-08 21:11:03 +01:00
// Find the first occurrence of the first character
int first = source.IndexOf(c0, 0, limit);
while (first != -1)
{
// Check if the following character is the same like
// the 2nd character of "pattern"
if (source[first + 1] != c1)
{
first = source.IndexOf(c0, ++first, limit - first);
continue;
}
// Check the rest of "pattern" (starting with the 3rd character)
2019-01-29 21:33:20 +01:00
var found = true;
for (int j = 2; j < pattern.Length; j++)
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
if (source[first + j] != pattern[j])
{
found = false;
break;
}
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
// If the whole word was found, return its index, otherwise try again
2019-01-19 14:40:37 +01:00
if (found)
{
return first;
}
2016-02-08 21:11:03 +01:00
first = source.IndexOf(c0, ++first, limit - first);
}
return -1;
}
public static int IndexOfAny(this string s, string[] words, StringComparison comparisonType)
{
if (words == null || string.IsNullOrEmpty(s))
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
return -1;
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
for (int i = 0; i < words.Length; i++)
{
var idx = s.IndexOf(words[i], comparisonType);
if (idx >= 0)
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
return idx;
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
}
return -1;
}
public static string FixExtraSpaces(this string s)
{
2019-01-19 14:40:37 +01:00
if (string.IsNullOrEmpty(s))
{
return s;
}
const char whiteSpace = ' ';
int k = -1;
for (int i = s.Length - 1; i >= 0; i--)
{
char ch = s[i];
if (k < 2)
{
if (ch == whiteSpace)
{
k = i + 1;
}
}
else if (ch != whiteSpace)
{
// only keep white space if it doesn't succeed/precede CRLF
int skipCount = (ch == '\n' || ch == '\r') || (k < s.Length && (s[k] == '\n' || s[k] == '\r')) ? 1 : 2;
// extra space found
if (k - (i + skipCount) >= 1)
{
s = s.Remove(i + 1, k - (i + skipCount));
}
// Reset remove length.
k = -1;
}
}
return s;
2016-02-08 21:11:03 +01:00
}
public static bool ContainsLetter(this string s)
{
if (s != null)
2016-02-08 21:11:03 +01:00
{
foreach (var index in StringInfo.ParseCombiningCharacters(s))
{
var uc = CharUnicodeInfo.GetUnicodeCategory(s, index);
if (uc == UnicodeCategory.LowercaseLetter || uc == UnicodeCategory.UppercaseLetter || uc == UnicodeCategory.TitlecaseLetter || uc == UnicodeCategory.ModifierLetter || uc == UnicodeCategory.OtherLetter)
2019-01-19 14:40:37 +01:00
{
return true;
2019-01-19 14:40:37 +01:00
}
}
2016-02-08 21:11:03 +01:00
}
return false;
}
public static string RemoveControlCharacters(this string s)
{
int max = s.Length;
var newStr = new char[max];
int newIdx = 0;
for (int index = 0; index < max; index++)
2016-02-08 21:11:03 +01:00
{
var ch = s[index];
if (!char.IsControl(ch))
{
newStr[newIdx++] = ch;
}
2016-02-08 21:11:03 +01:00
}
return new string(newStr, 0, newIdx);
2016-02-08 21:11:03 +01:00
}
public static string RemoveControlCharactersButWhiteSpace(this string s)
{
int max = s.Length;
var newStr = new char[max];
int newIdx = 0;
for (int index = 0; index < max; index++)
2016-02-08 21:11:03 +01:00
{
var ch = s[index];
if (!char.IsControl(ch) || ch == '\u000d' || ch == '\u000a' || ch == '\u0009')
{
newStr[newIdx++] = ch;
}
2016-02-08 21:11:03 +01:00
}
return new string(newStr, 0, newIdx);
2016-02-08 21:11:03 +01:00
}
public static string CapitalizeFirstLetter(this string s, CultureInfo ci = null)
{
var si = new StringInfo(s);
if (ci == null)
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
ci = CultureInfo.CurrentCulture;
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
if (si.LengthInTextElements > 0)
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
s = si.SubstringByTextElements(0, 1).ToUpper(ci);
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
if (si.LengthInTextElements > 1)
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
s += si.SubstringByTextElements(1);
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
return s;
}
public static string ToRtf(this string value)
{
return @"{\rtf1\ansi\ansicpg1252\deff0{\fonttbl\f0\fswiss Helvetica;}\f0\pard " + value.ToRtfPart() + @"\par" + Environment.NewLine + "}";
}
public static string ToRtfPart(this string value)
2016-02-08 21:11:03 +01:00
{
// special RTF chars
var backslashed = new StringBuilder(value);
backslashed.Replace(@"\", @"\\");
backslashed.Replace(@"{", @"\{");
backslashed.Replace(@"}", @"\}");
backslashed.Replace(Environment.NewLine, @"\par" + Environment.NewLine);
// convert string char by char
var sb = new StringBuilder();
foreach (char character in backslashed.ToString())
{
if (character <= 0x7f)
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
sb.Append(character);
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
else
2019-01-19 14:40:37 +01:00
{
2016-02-08 21:11:03 +01:00
sb.Append("\\u" + Convert.ToUInt32(character) + "?");
2019-01-19 14:40:37 +01:00
}
2016-02-08 21:11:03 +01:00
}
return sb.ToString();
2016-02-08 21:11:03 +01:00
}
public static string FromRtf(this string value)
{
return RichTextToPlainText.ConvertToText(value);
}
2019-01-19 12:29:38 +01:00
public static string RemoveChar(this string value, char charToRemove)
2017-12-10 22:18:13 +01:00
{
char[] array = new char[value.Length];
int arrayIndex = 0;
for (int i = 0; i < value.Length; i++)
{
char ch = value[i];
2019-01-19 12:29:38 +01:00
if (ch != charToRemove)
2019-01-19 14:40:37 +01:00
{
2017-12-10 22:18:13 +01:00
array[arrayIndex++] = ch;
2019-01-19 14:40:37 +01:00
}
2017-12-10 22:18:13 +01:00
}
return new string(array, 0, arrayIndex);
}
2018-01-23 11:12:58 +01:00
/// <summary>
/// Count characters excl. white spaces/ssa-tags/html-tags and normal space depending on parameter.
/// </summary>
public static int CountCharacters(this string value, bool removeNormalSpace)
2017-12-20 20:13:57 +01:00
{
2018-01-23 11:12:58 +01:00
int length = 0;
2017-12-20 20:13:57 +01:00
const char zeroWidthSpace = '\u200B';
const char zeroWidthNoBreakSpace = '\uFEFF';
char normalSpace = removeNormalSpace ? ' ' : zeroWidthSpace;
2018-01-23 11:12:58 +01:00
bool ssaTagOn = false;
bool htmlTagOn = false;
2019-01-29 21:33:20 +01:00
var max = value.Length;
for (int i = 0; i < max; i++)
2017-12-20 20:13:57 +01:00
{
char ch = value[i];
2018-01-23 11:12:58 +01:00
if (ssaTagOn)
{
if (ch == '}')
2019-01-19 14:40:37 +01:00
{
2018-01-23 11:12:58 +01:00
ssaTagOn = false;
2019-01-19 14:40:37 +01:00
}
2018-01-23 11:12:58 +01:00
}
else if (htmlTagOn)
{
if (ch == '>')
2019-01-19 14:40:37 +01:00
{
2018-01-23 11:12:58 +01:00
htmlTagOn = false;
2019-01-19 14:40:37 +01:00
}
2018-01-23 11:12:58 +01:00
}
else if (ch == '{' && i < value.Length - 1 && value[i + 1] == '\\')
{
ssaTagOn = true;
}
else if (ch == '<' && i < value.Length - 1 && (value[i + 1] == '/' || char.IsLetter(value[i + 1])) && value.IndexOf('>', i) > 0)
{
htmlTagOn = true;
}
else if (ch != '\n' && ch != '\r' && ch != '\t' && ch != zeroWidthSpace && ch != zeroWidthNoBreakSpace && ch != normalSpace)
{
length++;
}
2017-12-20 20:13:57 +01:00
}
2018-01-23 11:12:58 +01:00
return length;
2017-12-20 20:13:57 +01:00
}
2016-02-08 21:11:03 +01:00
}
}