Alex
Alex

Reputation: 165

subtracting the value of strings

I'm trying to understand the following code. But I was having a hard time finding anything so I want to make sure I'm understanding it correctly. So please correct me if I'm wrong.

string choice = txtProduct.Text.ToUpper();
char coordX = choice[0];
int indexX = coordX - 'A';

What I think is happening is that each string letter (A, B, C etc..) has a value so coordX - 'A'; is just subtracting those values.

So if the user entered "A" it would be 'A' - 'A' which would be 0 if the user entered "B" it would be 'B' - 'A' which would be 1. etc.

Upvotes: 0

Views: 115

Answers (3)

Aram
Aram

Reputation: 5705

What is really happening is when you run this line:

int indexX = coordX - 'A';

it casts your Char to its ASCII number and then subtracts the ASCIIs and returns the result...

This is probably more clrear:

int indexX = (int)coordX - (int)'A';

So: 'A' is 65 and 'B' = 66 in ASCII, so that's how you get the result you see..

Upvotes: 1

Kapoor
Kapoor

Reputation: 1428

Yes, U r correct. Perhaps its written with an intention to find first character's sequence order as per abcdefghijklmnopqrstuvwxyz

Upvotes: 1

Ygalbel
Ygalbel

Reputation: 5519

You right, this code return you index of the letter in alphabet.

Upvotes: 1

Related Questions