So the issuie is that i don't undertsand why out is not compatible with the char. Because when I created a simular program but starting of the line of code where the issuie is with an int it worked out fine. The worng code is that the out gives error. Can someone please explain whats more compatible? Thanks in advance :)
string Input = TxbG.Text.ToString();
Convert(Input);
}
void Convert(string Input)
{
char Output; bool Try = char.IsUpper(Input, **out** Output);
string Return = Input.ToString();
if (Try == true)
{
Return.ToUpper();
}
else
{
Return.ToLower();
}
TxbV.Text = (Return);*emphasized text*
Char.IsUpper will check only a single character and by looking at your example you are trying to check an entire string. You can check each character one by one but not an entire string. Also the method Char.IsUpper has two overloads. One is a single character and the other is a string with the character index. So the out worked with int because it was able to recognize a method with int parameter. You can try the following code for checking the string
bool IsAllUpper(string input)
{
for (int i = 0; i < input.Length; i++)
{
if (!Char.IsUpper(input[i]))
return false;
}
return true;
}
Related
I've got an extension method that converts me ulong into a string value with some kind of encryption. I want to output them as they are just by using Console.WriteLine, in most scenarios it works but there is a problem with values with escapes characters. For example "(V\\\|RN" outputs just "(V\|RN".
var result = id.IdToCode();
Console.WriteLine(result);
or
Console.WriteLine(id.IdToCode());
The method IdToCode returns stringBuilder.ToString()
I've tried many combinations with putting somewhere # to return the string as it is but without any result. Maybe I should override the default behavior of Console.WriteLine or the stringBuilder.ToString() is the problem here?
Here is a screen of what I mean.
And below the code of IdToCode method:
public static string IdToCode(this ulong value)
{
const string charArray = #"1234890qwertyuiopbnmQWERTYUasdfghjklzxcvIOPASDFGHJKLZXCVBNM!+={}[]|\<>?##567$%^&*()-_";
StringBuilder stringBuilder = new StringBuilder();
ulong num = value;
while (num != 0UL)
{
ulong index = num % (ulong)charArray.Length;
num /= (ulong)charArray.Length;
stringBuilder.Insert(0, charArray[(int)index].ToString());
}
return stringBuilder.ToString();
}
I've changed the char array into different one but the general method it's the same as above.
The problem is you need to use the # in front of the string literal which actually adds the backslash to the StringBuilder.
There is no point in doing #id.IdToCode(), because when the string is returned, it already contains (V\|RN. The tooltip shows \\ because it shows the escaped eversion - meaning the single backslash.
One thing that is certain is that the problem can't be resolved here, but only inside the IdToCode method, where it actually originates.
Compare this (same as your code):
static void Main(string[] args)
{
var str = IdToCode();
Console.WriteLine();
}
public static string IdToCode()
{
return "(\\VN";
}
Hovering over str I see (\\VN - two backslashes, output is just one backslash - which is correct.
And this:
static void Main(string[] args)
{
var str = IdToCode();
Console.WriteLine();
}
public static string IdToCode()
{
return #"(\\VN";
}
Here the tooltip shows "(\\\\VN" which is again correct - there are two actual backslashes and console output is the desired (\\VN
I am trying to check if value exists in a string array. The below one works but when I tried the next code block, it failed.
bool exixts;
string toCheck= "jupiter";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck))
{
exists = true;
}
How can I check for trim and case sensitivity?
I tried this
bool exixts;
string toCheck= "jupiter ";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
{
exists = true;
}
The IEnumerable<string>.Contains(value, comparer) expects a compare class instance, not an enum value.
The library does have some ready made comparers available though:
//if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
if (printer.Contains(toCheck.Trim(), StringComparer.OrdinalIgnoreCase))
Or you can do like this,
bool exists = printer.Any(x=> x == toCheck.Trim());
Hope helps,
This question already has answers here:
How to check first character of a string if a letter, any letter in C#
(4 answers)
Closed 8 years ago.
i need some help. I have to write a programm where you can do some calculation with matrices.
The User input should be for example: A=[1,2,3;4,5,6;7,8,9]
The user should be able to save up to 10 matrices. The user should be able to write operations like A+B or C*D
I want to check, if the first character of the users input is a letter, if not, i want to give an exception. Is there a method in c# where you can check if the first character is a letter. I want to save the letters into a string array so I can reference the name of the matrices to the int [,] which contains the matrices. Here is a snippet of my code:
int i = 0;
int[][,] ArrayContainer = new int[10][,];
int rowcount;
int columncount;
while (i < 10)
{
string input = Console.ReadLine();
string trimedinput;
if (input.Contains(" "))
{
trimedinput = input.Replace(" ", string.Empty);
}
else if (input == String.Empty)
{
break;
}
else if(!input.Contains("="))
{
Console.WriteLine("The definition of your matrix is not correct. Please type in 'help' if you need help.");
continue;
}
else
{
trimedinput = input;
}
}
Thank you for help!
you can use Char.IsLetter as shown below :-
for example :-
string str = " I am a string";
bool isLetter = !String.IsNullOrEmpty(str) && Char.IsLetter(str[0]);
For more information :-
http://msdn.microsoft.com/en-us/library/system.char.isletter.aspx
Use Char.IsLetter.
bool isLetter = Char.IsLetter(str[0]);
You could use char.IsLetter():
string foo = "Hello world";
bool isLetter = char.IsLetter(foo, 0);
You could use the the method IsLetter of Char type.
For instance if you have a string called test and you want to check if it's first character is a letter, you could check it out like below:
bool isLetter = Char.IsLetter(test[0])
For further documenation, please have a look here.
I am working on a simple windows forms application that the user enters a string with delimiters and I parse the string and only get the variables out of the string.
So for example if the user enters:
2X + 5Y + z^3
I extract the values 2,5 and 3 from the "equation" and simply add them together.
This is how I get the integer values from a string.
int thirdValue
string temp;
temp = Regex.Match(variables[3], #"\d+").Value
thirdValue = int.Parse(temp);
variables is just an array of strings I use to store strings after parsing.
However, I get the following error when I run the application:
Input string was not in a correct format
Why i everyone moaning about this question and marking it down? it's incredibly easy to explain what is happening and the questioner was right to say it as he did. There is nothing wrong whatsoever.
Regex.Match(variables[3], #"\d+").Value
throws a Input string was not in a correct format.. FormatException if the string (here it's variables[3]) doesn't contain any numbers. It also does it if it can't access variables[3] within the memory stack of an Array when running as a service. I SUSPECT THIS IS A BUG The error is that the .Value is empty and the .Match failed.
Now quite honestly this is a feature masquerading as a bug if you ask me, but it's meant to be a design feature. The right way (IMHO) to have done this method would be to return a blank string. But they don't they throw a FormatException. Go figure. It is for this reason you were advised by astef to not even bother with Regex because it throws exceptions and is confusing. But he got marked down too!
The way round it is to use this simple additional method they also made
if (Regex.IsMatch(variables[3], #"\d+")){
temp = Regex.Match(variables[3], #"\d+").Value
}
If this still doesn't work for you you cannot use Regex for this. I have seen in a c# service that this doesn't work and throws incorrect errors. So I had to stop using Regex
I prefer simple and lightweight solutions without Regex:
static class Program
{
static void Main()
{
Console.WriteLine("2X + 65Y + z^3".GetNumbersFromString().Sum());
Console.ReadLine();
}
static IEnumerable<int> GetNumbersFromString(this string input)
{
StringBuilder number = new StringBuilder();
foreach (char ch in input)
{
if (char.IsDigit(ch))
number.Append(ch);
else if (number.Length > 0)
{
yield return int.Parse(number.ToString());
number.Clear();
}
}
yield return int.Parse(number.ToString());
}
}
you can change the string to char array and check if its a digit and count them up.
string temp = textBox1.Text;
char[] arra = temp.ToCharArray();
int total = 0;
foreach (char t in arra)
{
if (char.IsDigit(t))
{
total += int.Parse(t + "");
}
}
textBox1.Text = total.ToString();
This should solve your problem:
string temp;
temp = Regex.Matches(textBox1.Text, #"\d+", RegexOptions.IgnoreCase)[2].Value;
int thirdValue = int.Parse(temp);
I am using C# and I want to convert a string to int to verify name. For example ** or 12 is not a name. I just want to convert the string into ASCII values and then will verify the name. How do I do that?
Converting back and forth is simple:
int i = int.Parse("42");
string s = i.ToString();
If you do not know that the input string is valid, use the int.TryParse() method.
From what I understand, you want to verify that a given string represents a valid name? I'd say you should probably provide more details as to what constitutes a valid name to you, but I can take a stab at it. You could always iterate over all the characters in the string, making sure they're letters or white space:
public bool IsValidName(string theString)
{
for (int i = 0; i < theString.Length - 1; i++)
{
if (!char.IsLetter(theString[i]) && !char.IsWhiteSpace(theString[i]))
{
return false;
}
}
return true;
}
Of course names can have other legitimate characters, such as apostrophe ' so you'd have to customize this a bit, but it's a starting point from what I understand your question truly is. (Evidently, not all white space characters would qualify as acceptable either.)
There multiple ways to convert:
try
{
string num = "100";
int value;
bool isSuccess = int.TryParse(num, out value);
if(isSuccess)
{
value = value + 1;
Console.WriteLine("Value is " + value);
}
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
It's not clear to me what you're trying to do, but you can get the ASCII codes for a string with this code:
System.Text.Encoding.ASCII.GetBytes(str)