Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
int n = 777;

            string x = n.ToString();

            Console.WriteLine(x[2]);

            if (x[2] == 7)

            {

                Console.WriteLine("no.7");

            }

//output-

//7



"no. 7" is not getting printed. Is there something which I haven't quite done right?

What I have tried:

Well, what could I have tried anyways?
Posted
Updated 27-Mar-16 3:21am
Comments
[no name] 27-Mar-16 9:08am    
Yes you missed something. The character representation of '7' (in x[2]) does not match to integer 7....

Becasue there is a big difference between 7 and '7'
The first is a number, the second is a character.
A string is made up of a sequence of characters, so 777 as a string is "777": three characters '7' following each other.
A character can contain '7', but it can also contain 'H', 'E', 'L', 'L', or 'O' - so trying to compare it to a numeric value only works if you use the value for the character in a right character set.
And so x[2] is a single character '7' which is not the same value as 7 the number.
Try this:
C#
if (x[2] == '7')
and it'll work.
 
Share this answer
 
Comments
[no name] 27-Mar-16 9:21am    
Good Explanation, a 5.
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

With the debugger, stop execution at the if and inspect variables, you will see what in x[2] and you will understand that 7 is not the same as "7".

You should read language documentation as soon as possible.
 
Share this answer
 
v2
Comments
[no name] 27-Mar-16 9:39am    
In this case I think Debugger is not relevant. OP should first understand character representation. Ok Debugger can help to visualize it... No vote from my side.
Patrice T 27-Mar-16 9:51am    
I agree that OP must read document as soon as possible, but knowing the debugger can't harm. and will show the problem in this case.

No vote is ok for me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900