As Panagiotis pointed out the representation of escape codes in a string is simply about visual representation and doesn't change the meaning or the encoding of the string. Yes, C# (and .NET in general) uses Unicode/UTF-16 to encode the strings in memory, but that's neither relevant to your question nor important in most cases.
That aside, your main question seems to be this:
what is the best way to can I remove the \a\a\r\r\r\r\r\a at string begining.
As with most such questions there are a lot of ways to approach this. Regular expressions (as Panagiotis suggested) can certainly do the job, but they can be finicky and are often slower than more direct options. There are times when a regular expression is the best fit for a particular problem, but this isn't necessarily one of those times. I don't get the impression you're looking for the fastest possible solution... but it doesn't hurt to explore options.
So here are a couple of ideas.
If you're looking to remove a small number of known characters from the start of the string then there's a string method for that: TrimStart()
. Specifically the version that accepts a set of characters to remove:
string cleanText = inputText.TrimLeft('\a', '\r', '\n');
That's fine for a small number of known characters. But if you're looking to remove any control character from the start of the string you can count them and skip that many characters from the string:
// Count control characters at the start of the string:
int count = 0;
for (; count < inputText.Length && Char.IsControl(inputText, count); count++)
{ }
// This monster is safe:
string cleanText =
count == 0 ? inputText :
count >= inputText.Length ? string.Empty :
inputText[count..];
This happens to be one of the fastest methods to do that particular job, but it's not the prettiest. And unless you're doing this frequently you're probably not going to miss a few extra milliseconds each time.
And since performance isn't a critical issue, let me introduce you to one of the slowest options: LINQ.
string cleanText = new string(inputText.SkipWhile(c => char.IsControl(c)).ToArray());
While the performance on this is frankly terrible, it's quite a bit more readable than the high-perforance version. SkipWhile()
skips items while the condition is met, the rest of the characters are collected into an array and used to create a new string. It's pretty but slow. Just like my cat.