c# cannot convert from string to char - c#

I am trying to write some code to display any symbols present in a password the user gives you. I am quite new and am trying to do use isSymbol but I am stuck. it says cannot convert from string to char
using System;
namespace booleanprok
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a made up password:");
string madeUppw = Console.ReadLine();
Console.WriteLine(char.IsSymbol(madeUppw));
}
}
}

"I am trying to write some code to display any symbols present in a password the user gives you."
Given the above statement, I see the following problems with the sample code given:
you're passing a string to the IsSymbol() method, which expects a char.
you're outputting the return value from the IsSymbol() method (which is a bool) instead of the characters themselves.
IsSymbol() does not return all characters that we typically consider symbols in a password (like !, #, #, etc). From the documentation: "symbols are members of the following categories in UnicodeCategory: MathSymbol, CurrencySymbol, ModifierSymbol, and OtherSymbol."
One way to solve these issues is to consider any character that's not alphabetic or numeric to be a "symbol", which we can do by using the Linq extension method Where() along with the char.IsLetter() and char.IsDigit() methods. Then we can output the characters to the console using string.Join on the results.
For example:
Console.Write("Enter a made up password: ");
string madeUpPwd = Console.ReadLine();
// Get the distinct characters that aren't Letters or Digits
IEnumerable<char> symbols = madeUpPwd
.Where(c => !char.IsLetter(c) && !char.IsDigit(c))
.Distinct();
// Output them to the console (separated by commas and wrapped in single quotes)
Console.WriteLine($"You entered the symbols: '{string.Join("', '", symbols)}'");
Sample Output
(Note that using .Where(char.IsSymbol) would have only return the '$' character)

char.IsSymbol accepts a char argument, but you're passing a parameter of type string. If you're sure the input will only be one character in length, or if you just want the first character and disregard others, you can call char.IsSymbol(madeUppw[0]);
However, you can force reading a single character with Console.ReadKey and get the value with KeyChar:
char madeUppw = Console.ReadKey().KeyChar;
Console.WriteLine(char.IsSymbol(madeUppw));

Convert string to char
Try this one
bool res;
Console.WriteLine("Enter a made up password:");
string madeUppw = Console.ReadLine();
foreach(char s in madeUppw){
res = Char.IsSymbol(s);//The char.issymbol takes characters as parameter
}
If you have a single character string, You can also try
string str = "A";
char character = char.Parse(str);
Or
string str = "A";
char character = str.ToCharArray()[0];

A string consists of 0 or more characters and for validating if any of the characters is an symbol, you need step through each of the characters in the string and validate them individually. You could do so using Enumerable.Any and char.IsSymbol as
string madeUppw = Console.ReadLine();
Console.WriteLine(madeUppw.Any(x=>char.IsSymbol(x)));
Enumerable.Any verifies whether any of the elements in the sequence (in this a string), exists or satisfies a condition (in this, condition is if any of the character is a Symbol).
The last line could further trimmed down as
Console.WriteLine(madeUppw.Any(char.IsSymbol));
If you need to print all the symbols in the string, you could use
Console.WriteLine(string.Join(",",madeUppw.Where(x=>char.IsSymbol(x))));

Related

convert non alphanumeric glyphs to unicode while preserving alphanumeric

I need to convert non alpha-numeric glyphs in a string to their unicode value, while preserving the alphanumeric characters. Is there a method to do this in C#?
As an example, I need to convert this string:
"hello world!"
To this:
"hello_x0020_world_x0021_"
To get string safe for XML node name you should use XmlConver.EncodeName.
Note that if you need to encode all non-alphanumeric characters you'd need to write it yourself as "_" is not encoded by that method.
You could start with this code using LINQ Select extension method:
string str = "hello world!";
string a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
a += a.ToLower();
char[] alphabet = a.ToCharArray();
str = string.Join("",
str.Select(ch => alphabet.Contains(ch) ?
ch.ToString() : String.Format("_x{0:x4}_", ch)).ToArray()
);
Now clearly it has some problems:
it does linear search in the list of characters
missed numeric...
if we add numeric need to decide if first character is ok to be digit (assuming yes)
code creates large number of strings that are immediately discarded (one per character)
alphanumeric is limited to ASCII (assuming ok, if not Char.IsLetterOrDigit to help)
does to much work for pure alpha-numeric strings
First two are easy - we can use HashSet (O(1) Contains) initialized by full list of characters (if any alpahnumeric characters are ok more readable to use existing method - Char.IsLetterOrDigit):
public static HashSet<char> asciiAlphaNum = new HashSet<char>
("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
To avoid ch.ToString() that really pointlessly produces strings for immediate GC we need to figure out how to construct string from mix of char and string. String.Join does not work because it wants strings to start with, regular new string(...) does not have option for mix of char and string. So we are left with StringBuilder that happily takes both to Append. Consider starting with initial size str.Length if most strings don't have other characters.
So for each character we just need to either builder.Append(ch) or builder.AppendFormat(("_x{0:x4}_", (int)ch). To perform iteration it is easier to just use regular foreach, but if one really wants LINQ - Enumerable.Aggregate is the way to go.
string ReplaceNonAlphaNum(string str)
{
var builder = new StringBuilder();
foreach (var ch in str)
{
if (asciiAlphaNum.Contains(ch))
builder.Append(ch);
else
builder.AppendFormat("_x{0:x4}_", (int)ch);
}
return builder.ToString();
}
string ReplaceNonAlphaNumLinq(string str)
{
return str.Aggregate(new StringBuilder(), (builder, ch) =>
asciiAlphaNum.Contains(ch) ?
builder.Append(ch) : builder.AppendFormat("_x{0:x4}_", (int)ch)
).ToString();
}
To the last point - we don't really need to do anything if there is nothing to convert - so some check like check alphanumeric characters in string in c# would help to avoid extra strings.
Thus final version (LINQ as it is a bit shorter and fancier):
private static asciiAlphaNumRx = new Regex(#"^[a-zA-Z0-9]*$");
public static HashSet<char> asciiAlphaNum = new HashSet<char>
("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
string ReplaceNonAlphaNumLinq(string str)
{
return asciiAlphaNumRx.IsMatch(str) ? str :
str.Aggregate(new StringBuilder(), (builder, ch) =>
asciiAlphaNum.Contains(ch) ?
builder.Append(ch) : builder.AppendFormat("_x{0:x4}_", (int)ch)
).ToString();
}
Alternatively whole thing could be done with Regex - see Regex replace: Transform pattern with a custom function for starting point.

How can I capitalize the first letter of each sentence in C# using char?

Sentence capitalization:
private string SentenceCapitalizer(string input)
{
char delim = '.';
string letter1;
string[] tokens = input.Split(delim);
foreach (string phrase in tokens)
{
letter1 = phrase.Remove(0);
letter1.ToUpper();
}
return input;
}
Please keep in mind that this is only one of the methods.
First, take a look at the signature of ToUpper() and notice it returns a string. This doesn't modify the string you call it on; rather it returns a new string result from that operation.
In your case you have the phrases already. You can take the first character of a phrase with phrase[0] or phrase.First(). You should also take a look at Substring which gives you a range of characters from a string.
Putting that all together you could do something like:
phrase = phrase[0].ToString().ToUpper() + phrase.Substring(1);
What this does is take the first character from phrase and turn it from a char to a string which is what you need to call ToUpper() which you then concatenate with the remainder of the phrase using Substring starting at position 1 (which is the second character) and assign it back to phrase.

c# operator == cannot be used (string to char)

How do I make it so the == does work on the string and char.
class Program
{
static void Main(string[] args)
{
string a;
// get random lowercase letter
Console.WriteLine(RandomLetter.GetLetter());
a = Console.ReadLine();
if (a == RandomLetter.GetLetter())
the Error
'Operator '==' cannot be applied to operands of type 'string' and 'char''
{
}
Console.ReadLine();
}
}
}
If you wanna read just a character use Console.ReadKey method
char random = RandomLetter.GetLetter();
Console.WriteLine(random);
char input = Console.ReadKey().KeyChar;
if (random == input)
(a == RandomLetter.GetLetter().ToString())
The ToString() override on all objects can be used to change anything into a string.
Here are some options:
if (a == RandomLetter.GetLetter().ToString()) ...
if (a.Length == 1 && a[0] == RandomLetter.GetLetter()) ...
But as other answers mention, in your particular case you're probably better off just reading one character from the console anyways.
Console.ReadLine() reads the whole line as a String, so it can't be compared directly to a single character. You either need to convert your character to a String, so it can be compared (.ToString()), or instead read a single key inputted by the user, e.g. using Console.ReadKey().KeyChar instead of Console.ReadLine().
You'll want to use the former if the idea is to allow the user to input a line of characters and check if it consists of a single, specified character. If you want to read a single key press, use the latter.
Try comparing just the first letter of the string to the char (because a string is just an array of type char). By doing it this way, if the user enters more than you want, the program wont crash.
char myChar = 'a';
string myString = "a";
if (myChar == myString[0])
{
Console.WriteLine("it's a match");
Console.ReadLine();
}
You could use:
Console.ReadKey().KeyChar to get only the first typed char.
Console.ReadLine().First(), but it allows the user to write an entire sequence of characters.
Be careful with the ReadKey method because it allows user to press SHIFT, CTRL or any other key even if they haven't a "written" representation, if you intend to compare only "writable" chars.

C# string to sentence

Is there a way to convert string without spaces to a proper sentence??
E.g. "WhoAmI" needs to be converted to "Who Am I"
A regex replacement would do this, if you're just talking about inserting a space before each capital letter:
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main()
{
var input = "WhoAmI";
var output = Regex.Replace(input, #"\p{Lu}", " $0").TrimStart();
Console.WriteLine(output);
}
}
However, I suspect there will be significant corner cases. Note that the above uses \p{Lu} instead of just [A-Z] to cope with non-ASCII capital letters; you may find A-Z simpler if you only need to deal with ASCII. The TrimStart() call is to remove the leading space you'd get otherwise.
If every word in the string is starting with uppercase you may just convert each part that is starting with uppercase to a space separated string.
You can use LINQ
string words = "WhoAmI";
string sentence = String.Concat(words.Select(letter => Char.IsUpper(letter) ? " " + letter
: letter.ToString()))
.TrimStart();

Unquote string in C#

I have a data file in INI file like format that needs to be read by both some C code and some C# code. The C code expects string values to be surrounded in quotes. The C# equivalent code is using some underlying class or something I have no control over, but basically it includes the quotes as part of the output string. I.e. data file contents of
MY_VAL="Hello World!"
gives me
"Hello World!"
in my C# string, when I really need it to contain
Hello World!
How do I conditionally (on having first and last character being a ") remove the quotes and get the string contents that I want.
On your string use Trim with the " as char:
.Trim('"')
I usually call String.Trim() for that purpose:
string source = "\"Hello World!\"";
string unquoted = source.Trim('"');
My implementation сheck that quotes are from both sides
public string UnquoteString(string str)
{
if (String.IsNullOrEmpty(str))
return str;
int length = str.Length;
if (length > 1 && str[0] == '\"' && str[length - 1] == '\"')
str = str.Substring(1, length - 2);
return str;
}
Just take the returned string and do a Trim('"');
Being obsessive, here (that's me; no comment about you), you may want to consider
.Trim(' ').Trim('"').Trim(' ')
so that any, bounding spaces outside of the quoted string are trimmed, then the quotation marks are stripped and, finally, any, bounding spaces for the contained string are removed.
If you want to retain contained, bounding white space, omit the final .Trim(' ').
Should there be embedded spaces and/or quotation marks, they will be preserved. Chances are, such are desired and should not be deleted.
Do some study as to what a no argument Trim() does to things like form feed and/or tabulation characters, bounding and embedded. It could be that one and/or the other Trim(' ') should be just Trim().
If you know there will always be " at the end and beginning, this would be the fastest way.
s = s.Substring(1, s.Length - 2);
Use string replace function or trim function.
If you just want to remove first and last quotes use substring function.
string myworld = "\"Hello World!\"";
string start = myworld.Substring(1, (myworld.Length - 2));
I would suggest using the replace() method.
string str = "\"HelloWorld\"";
string result = str.replace("\"", string.Empty);
What you are trying to do is often called "stripping" or "unquoting". Usually, when the value is quoted that means not only that it is surrounded by quotation characters (like " in this case) but also that it may or may not contain special characters to include quotation character itself inside quoted text.
In short, you should consider using something like:
string s = #"""Hey ""Mikey""!";
s = s.Trim('"').Replace(#"""""", #"""");
Or when using apostrophe mark:
string s = #"'Hey ''Mikey''!";
s = s.Trim('\'').Replace("''", #"'");
Also, sometimes values that don't need quotation at all (i.e. contains no whitespace) may not need to be quoted anyway. That's the reason checking for quotation characters before trimming is reasonable.
Consider creating a helper function that will do this job in a preferable way as in the example below.
public static string StripQuotes(string text, char quote, string unescape)a
{
string with = quote.ToString();
if (quote != '\0')
{
// check if text contains quote character at all
if (text.Length >= 2 && text.StartsWith(with) && text.EndsWith(with))
{
text = text.Trim(quote);
}
}
if (!string.IsNullOrEmpty(unescape))
{
text = text.Replace(unescape, with);
}
return text;
}
using System;
public class Program
{
public static void Main()
{
string text = #"""Hello World!""";
Console.WriteLine(text);
// That will do the job
// Output: Hello World!
string strippedText = text.Trim('"');
Console.WriteLine(strippedText);
string escapedText = #"""My name is \""Bond\"".""";
Console.WriteLine(escapedText);
// That will *NOT* do the job to good
// Output: My name is \"Bond\".
string strippedEscapedText = escapedText.Trim('"');
Console.WriteLine(strippedEscapedText);
// Allow to use \" inside quoted text
// Output: My name is "Bond".
string strippedEscapedText2 = escapedText.Trim('"').Replace(#"\""", #"""");
Console.WriteLine(strippedEscapedText2);
// Create a function that will check texts for having or not
// having citation marks and unescapes text if needed.
string t1 = #"""My name is \""Bond\"".""";
// Output: "My name is \"Bond\"."
Console.WriteLine(t1);
// Output: My name is "Bond".
Console.WriteLine(StripQuotes(t1, '"', #"\"""));
string t2 = #"""My name is """"Bond"""".""";
// Output: "My name is ""Bond""."
Console.WriteLine(t2);
// Output: My name is "Bond".
Console.WriteLine(StripQuotes(t2, '"', #""""""));
}
}
https://dotnetfiddle.net/TMLWHO
Here's my solution as extension method:
public static class StringExtensions
{
public static string UnquoteString(this string inputString) => inputString.TrimStart('"').TrimEnd('"');
}
It's just trimming at the start an the end...

Categories

Resources