Home > database >  Convert special character in string into a char
Convert special character in string into a char

Time:09-22

I have this string:

string specialCharacterString = @"\n";

where "\n" is the new line special character.

Is it possible convert/assign that string (of two characters) into a (single) char. How do I do something like:

char specialCharacter = Parse(specialCharacterString);

Where specialCharacter value would be equal to \n

Is there anything in dotnet that would parse the string for me or must I use if or switch the string (the string can contain any special character) to accomplish what I want. Note that char.Parse(string) cannot handle special characters and thinks the string above is actually two characters.

CodePudding user response:

Maybe I am oversimplifying but can't you just do the following:

txtString.Replace("\n", "$");

It is technically a string to string replacement but would be string to char... You can always cast it to a char since you know what char you are replacing the string with.

CodePudding user response:

Not sure, what business need it is, but if you need parsing C# in C# you can use some tools like Antlr, which supports C# grammar (https://github.com/antlr/grammars-v4/)

I don't think there is any ready tool designed just for strings

CodePudding user response:

Try use Regex.Unescape(specialCharacterString);

It will return the new string with escape characters.

For example:

var literalStringWithEscapeCharacters = @"Hello\tWorld";
var stringWithEscapeCharacters = Regex.Unescape(literalStringWithEscapeCharacters);
Console.WriteLine(stringWithEscapeCharacters);

Will print: Hello World

Instead of: Hello\tWorld

Then you can find escape characters in stringWithEscapeCharacters like this:

var escapeChars= new [] { '\n' };
var characters = stringWithEscapeCharacters.Where(c => escapeChars.Contains(c)).ToList();

All escape characters described here:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#string-escape-sequences

CodePudding user response:

foreach(char ch in str)
{
    // do something with char
}
  •  Tags:  
  • c#
  • Related