i am trying to return an index based on the input of an user, the input is 2 characters only, like, a1, b2, c3...
public int returnInt(string x)
{
if (x == "a")
return 0;
else if (x == "b")
return 1;
else if (x == "c")
return 2;
else if (x == "d")
return 3;
else if (x == "e")
return 4;
else if (x == "f")
return 5;
else if (x == "g")
return 6;
else if (x == "h")
return 7;
else if (x == "1")
return 0;
else if (x == "2")
return 1;
else if (x == "3")
return 2;
else if (x == "4")
return 3;
else if (x == "5")
return 4;
else if (x == "6")
return 5;
else if (x == "7")
return 6;
else if (x == "8")
return 7;
return 0;
}
And this is where i use the method:
var toMove = myButtonArray[returnInt(totxt.Text.Substring(0)), returnInt(totxt.Text.Substring(1))];
the method works fine for the second substring, but it doesn't work for the first substring(0). Can anyone help me about this? When I type a1, program should return to 1 and 1 but it only returns 0 for the first substring.
CodePudding user response:
Since your input string is always 2 characters only, and you want to use them as index for your 2-d array, you need to change your code to below:
var toMove = myButtonArray[returnInt(totxt.Text.Substring(0,1)),
returnInt(totxt.Text.Substring(1,1))];
This way you are saying to String.Substring function to return 1 character at a time, and mentioning the start index as first input argument.
CodePudding user response:
Let's operate with single characters, not strings:
public int returnInt(char x) =>
x >= 'a' && x <= 'h' ? x - 'a'
: x >= '1' && x <= '8' ? x - '1'
: 0;
Then you can put:
var toMove = myButtonArray[returnInt(totxt.Text[0]), returnInt(totxt.Text[1])];
please, note, that we get 0th and 1st char
, not string