检查字符串的最后一位是奇数还是c#

时间:2016-11-23 07:39:55

标签: c#

我有一个问题是从字符串中获取最后一位数字。

//read data from MS Excel
while (reader.Read())
{
    dataGridView1.Rows.Add();
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Id"].Value = reader[0].ToString();
   dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Name"].Value = reader[1].ToString();
   dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["DateOfBirth"].Value = reader[2].ToString();
}

// then I want to save the data into database from excel
// so i want to write code to check the id
// for example : id = "030711026098"
while (reader.Read())
{
    id = reader[0].ToString();
    name = reader[1].ToString();
    dob = reader[2].ToString();
    gender = ??
    // Gender will be decided based on the id
    // if the last digit is odd, then gender = male
    // if the last digit is even, then gender = female
}
// do the insert

4 个答案:

答案 0 :(得分:1)

String id = "030711026098"
char last = id[id.Length-1];
if(Convert.ToInt32(last) % 2 ==0)
//female
else 
//male

使用字符串长度获取字符串的最后一个字符。将它转换为整数并检查它是否可以被2整除。如果它是可分的那么它是偶数的,因此男性也是女性。

答案 1 :(得分:1)

 id = "030711026098";

// get last char of the string 
char lastChar = id.substr(id.length - 1);
// convert last number to an integer 
int number = Convert.ToInt32(lastChar);
// this returns true if number is odd
bool isOdd = return number % 2 != 0;

if(isOdd)
 //female
else 
 //male

或者一行:

 string gender = Convert.ToInt32(id.Substring(id.Length - 1)) % 2 != 0 ? "female" : "male";

答案 2 :(得分:0)

String id = "030711026098";
bool isLastCharOdd = (Convert.ToInt32(id[id.Length-1])) % 2 != 0;
if(isLastCharOdd)
   //male
else
   //female

答案 3 :(得分:0)

我已将整个事物转换为int64,因为长度始终是固定的。

 string temp = "030711026099";
 long i = Convert.ToInt64(temp);
 if (i % 2 == 0)
 {
    Console.WriteLine("Female");
 }
 else
 {
    Console.WriteLine("Male");
 }