/*
* GNU AFFERO GENERAL PUBLIC LICENSE
* Version 3, 19 November 2007
* Copyright (C) 2007 Free Software Foundation, Inc.
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/
using System;
using System.ComponentModel;
using System.Text;
namespace UVtools.Core.Extensions;
public static class StringExtensions
{
public static string RemoveFromEnd(this string input, int count)
{
return input.Remove(input.Length - count);
}
///
/// Upper the first character in a string
///
/// Input string
/// Modified string with fist character upper
public static string FirstCharToUpper(this string input)
{
return input switch
{
null => throw new ArgumentNullException(nameof(input)),
"" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)),
_ => $"{char.ToUpper(input[0])}{input[1..]}"
};
}
///
/// Repeat this string times
///
/// String to repeat
/// Number of times to repeat
/// repeated times
public static string Repeat(this string str, int count)
=> count <= 0 ? string.Empty : new StringBuilder(str.Length * count).Insert(0, str, count).ToString();
///
/// Converts a string into a target type
///
/// Target type to convert into
/// Value
/// Converted value into target type
public static T? Convert(this string input)
{
var converter = TypeDescriptor.GetConverter(typeof(T));
//Cast ConvertFromString(string text) : object to (T)
var result = converter.ConvertFromString(input);
if (result is null) return default;
return (T) result;
}
}