Jerameel Resco
Jerameel Resco

Reputation: 3629

Trimming a string in C#

I am trimming a string data type that has a value of \t in C# .NET 3.5. I have used the method .SubString() and converted it on a char data type but still it won't work.

It returns "\" as a char.

I wanted to get the value of "\t" instead of \t or "\";

Here's my code:

string sample = "\\t";

char val = Convert.ToChar(sample.Substring(0, 1));

Thanks in advance.

Upvotes: 0

Views: 208

Answers (4)

Jonathan Wood
Jonathan Wood

Reputation: 67345

"\\t" specifies a backslash (\\) followed by a t (t). Since Substring(0, 1) returns the first character, it would return the backslash.

Upvotes: 2

Justin Morgan
Justin Morgan

Reputation: 2435

You can use string literals to reduce this confusion.

string a = "hello \t world";   // hello     world
string b = @"hello \t world";  // hello \t world

Upvotes: 1

user197015
user197015

Reputation:

It kind of sounds like you are trying to remove occurrences of tabs (\t) from a string? If that's the case, you can use the Trim function: s.Trim('\t').

There's also TrimStart and TrimEnd, to remove from the start only or from the end only. If you want to remove all occurrences of tabs from the string, you can do s = s.Replace("\t",string.Empty).

Upvotes: 0

Mark Cidade
Mark Cidade

Reputation: 100047

Instead of "\\t", just use "\t", with one slash.

Upvotes: 2

Related Questions