在C#编程中,有许多有用的代码片段可以帮助开发者解决常见问题。以下是一些常用的C#代码片段,可以帮助您更有效地进行开发:
public static string ReverseString(string input)
{
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public static bool IsNullOrWhiteSpace(string input)
{
return string.IsNullOrWhiteSpace(input);
}
public static int StringToInt(string input)
{
return int.Parse(input);
}
public static DateTime StringToDate(string input)
{
return DateTime.Parse(input);
}
public static T StringToEnum<T>(string input)
{
return (T)Enum.Parse(typeof(T), input, true);
}
public static bool StringToBool(string input)
{
return bool.Parse(input);
}
public static byte[] StringToByteArray(string input)
{
return Encoding.UTF8.GetBytes(input);
}
public static string ToUpper(string input)
{
return input.ToUpper();
}
public static string ToLower(string input)
{
return input.ToLower();
}
public static bool ContainsString(string input, string value)
{
return input.Contains(value);
}
public static string RemoveWhitespace(string input)
{
return new string(input.ToCharArray().Where(c => !char.IsWhiteSpace(c)).ToArray());
}
public static string[] SplitString(string input, char separator)
{
return input.Split(separator);
}
public static string JoinStrings(string[] input, string separator)
{
return string.Join(separator, input);
}
public static int CountSubstringOccurrences(string input, string substring)
{
int count = 0;
int i = 0;
while ((i = input.IndexOf(substring, i)) != -1)
{
count++;
i += substring.Length;
}
return count;
}
public static string ReplaceSubstring(string input, string oldValue, string newValue)
{
return input.Replace(oldValue, newValue);
}
public static string RemoveDuplicateCharacters(string input)
{
return new string(input.Distinct().ToArray());
}
public static int StringLength(string input)
{
return input.Length;
}
public static bool StartsWith(string input, string value)
{
return input.StartsWith(value);
}
public static bool EndsWith(string input, string value)
{
return input.EndsWith(value);
}
public static string Substring(string input, int startIndex, int length)
{
return input.Substring(startIndex, length);
}
public static string[] StringToWords(string input)
{
return input.Split(new char[] { ' ', '.', ',' }, StringSplitOptions.RemoveEmptyEntries);
}
public static int StringToHash(string input)
{
return input.GetHashCode();
}
public static string StringToBase64(string input)
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(bytes);
}
public static string Base64ToString(string input)
{
byte[] bytes = Convert.FromBase64String(input);
return Encoding.UTF8.GetString(bytes);
}
public static string StringToUrlEncode(string input)
{
return WebUtility.UrlEncode(input);
}
public static string UrlDecodeToString(string input)
{
return WebUtility.UrlDecode(input);
}
public static string StringToHtmlEncode(string input)
{
领取专属 10元无门槛券
手把手带您无忧上云