Reputation: 11
I need a program that will filter out and show only capital letters from a string. I have an example string:
c5hDF(5HА_Z*u1BP
I'm supposed to get:
DFHAZBP
I tried this:
string a = Console.ReadLine();
I couldn't use 'a' in an IF statement because there is an error that says
Error CS0200 Property or indexer 'string.this[int]' cannot be assigned to -- it is read only
I tried doing it a very long way because I can't think of another way. I basically told the program to check every part of the string if it is a capital letter like this:
for (i = 0; i < a.Length; i++)
{
if (a[i] = "Q")
{
b = b + a[i];
}
}
I was thinking about doing it for every letter but it doesn't work. Also I tried:
string v = a;
and then type v in all the 'if's' but that didn't work either.
Upvotes: 0
Views: 65
Reputation: 393
You can simply use the IsUpper() for your desired output. I have tried the code as per your requirements. Kindly refer the following code.
static void Main(string[] args)
{
string text = "IsHanKsHaH";
char[] charArray = text.ToCharArray();
foreach(var ch in charArray)
{
if(Char.IsUpper(ch))
{
Console.Write(ch);
}
}
Console.ReadLine();
}
The output will be IHKHH
Upvotes: 0
Reputation: 4535
Like AKX said you just have a simple typo.
However, it seems like you intend do check every string character against A, B, C, and so on, which is very cumbersome and not really needed. The framework already has char.IsUpper to check if a character is an uppercase letter.
Also instead of a loop you could use LINQ to simplify your code:
var b = new string(a.Where(char.IsUpper).ToArray());
For a = "c5hDF(5HА_Z*u1BP"
this yields b = "DFHАZBP"
.
This takes your string a
and turns it via LINQ to a sequence of characters, then filters these on if they are uppercase, converting the filtered sequence to an array, which can then be used by using a string constructor to convert it to a string.
Upvotes: 1
Reputation: 169052
Simple typo:
if (a[i] = "Q")
should be
if (a[i] == "Q")
for a comparison, not assignment.
Upvotes: 2