Mohsen
Mohsen

Reputation: 343

How to concatenate string with a backslash with another string

How can I concatenate the string "\u" with "a string" to get "\u0000"?

My code creates two backslashes:

string a = @"\u" + "0000";  //ends up being "\\\u0000";

Upvotes: 4

Views: 12399

Answers (5)

David R Tribble
David R Tribble

Reputation: 12214

If I understand you correctly, I think you want to build a single-char string from an arbitrary Unicode value (4 hex digits). So given the string "0000", you want to convert that into the string "\u0000", i.e., a string containing a single character.

I think this is what you want:

string  f = "0000";    // Or whatever
int     n = int.Parse(f, NumberStyles.AllowHexSpecifier);
string  s = ((char) n).ToString();

The resulting string s is "\u0000", which you can then use for your search.

(With corrections suggested by Thomas Levesque.)

Upvotes: 5

Marcelo Cantos
Marcelo Cantos

Reputation: 186118

The escape sequence \uXXXX is part of the language's syntax and represents a single Unicode character. By contrast, @"\u" and "0000" are two different strings, with a total of six characters. Concatenating them won't magically turn them into a single Unicode escape. If you're trying to convert a Unicode code point into a single-character string, do this:

char.ConvertFromUtf32(strUnicodeOfMiddleChar).ToString()

BTW, don't use == true; it's redundant.

Upvotes: 4

Brian
Brian

Reputation: 5119

Escape your characters correctly!!

Both:

// I am an escaped '\'.   
string a = "\\u" + "0000";

And:

// I am a literal string.
string a = @"\u" + "0000";

Will work just fine. But, and I am going out on a limb here, I am guessing that you are trying to escape a Unicode Character and Hex value so, to do that, you need:

// I am an escaped Unicode Sequence with a Hex value.
char a = '\uxxxx';

Upvotes: 2

Yosi Dahari
Yosi Dahari

Reputation: 7009

Nope, that string really has single backslash in. Print it out to the console and you'll see that.

Upvotes: 2

Thomas Levesque
Thomas Levesque

Reputation: 292735

the line below creates tow backslash:

string a = @"\u" + "0000"; //a ends up being "\\u0000";

No, it doesn't; the debugger shows "\" as "\", because that's how you write a backslash in C# (when you don't prefix the string with @). If you print that string, you will see \u0000, not \\u0000.

Upvotes: 2

Related Questions