public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
string original = "abc123def456";
string result = GetAlphabeticPart(original);
Console.WriteLine(result); // 输出: abcdef
Console.ReadKey();
}
//方法1
public static string GetAlphabeticPart(string input)
{
StringBuilder sb = new StringBuilder(input.Length);
foreach (char c in input)
{
if (char.IsLetter(c))
{
sb.Append(c);
}
}
return sb.ToString();
}
//方法2
public static string GetAlphabeticPart(string input)
{
Span<char> buffer = stackalloc char[input.Length];
int index = 0;
foreach (char c in input)
{
if (char.IsLetter(c))
{
buffer[index++] = c;
}
}
return new string(buffer.Slice(0, index));
}
//方法3
public static string GetAlphabeticPart(string input)
{
int length = 0;
foreach (char c in input)
{
if (char.IsLetter(c))
{
length++;
}
}
return string.Create(length, input, (chars, str) =>
{
int index = 0;
foreach (char c in str)
{
if (char.IsLetter(c))
{
chars[index++] = c;
}
}
});
}
}