Bài viết này tôi sẽ hướng dẫn cách chuyển đổi kiểu dữ liệu string thành kiểu dữ liệu int trong ngôn ngữ lập trình C#. |
Int32.TryParse
Chuyển đổi các chuỗi ký tự(string) của một số nguyên tương đương INT 32-bit. Một giá trị sẽ trả về cho dù việc chuyển đổi có thành công hay không(nó trả về giá trị 0 khi không thành công) cho giá trị được gán. Riêng bản thân hàm thì sẽ trả về giá trị True Flase.
Cú pháp - Syntax
public static bool TryParse(
string s,
out int result
)
string s,
out int result
)
Ví dụ - Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HowToConvertStringToInt
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine();
int intValue01 = Int32.Parse("01234");
System.Console.WriteLine("-- intValue01: " + intValue01);
int intValue02 = 0;
Int32.TryParse("56789", out intValue02);
System.Console.WriteLine("-- intValue02: " + intValue02);
int intValue03 = 0;
if (Int32.TryParse("ABCD", out intValue03))
{
System.Console.WriteLine("-- intValue03: " + intValue03);
}
else
{
System.Console.WriteLine("-- intValue01 isn't valid! - Result return: " + intValue03);
}
System.Console.WriteLine("-- VNLIVES.NET ------------------");
System.Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HowToConvertStringToInt
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine();
int intValue01 = Int32.Parse("01234");
System.Console.WriteLine("-- intValue01: " + intValue01);
int intValue02 = 0;
Int32.TryParse("56789", out intValue02);
System.Console.WriteLine("-- intValue02: " + intValue02);
int intValue03 = 0;
if (Int32.TryParse("ABCD", out intValue03))
{
System.Console.WriteLine("-- intValue03: " + intValue03);
}
else
{
System.Console.WriteLine("-- intValue01 isn't valid! - Result return: " + intValue03);
}
System.Console.WriteLine("-- VNLIVES.NET ------------------");
System.Console.ReadLine();
}
}
}
Kết quả - Result.
Write: +Bui Ngoc Son
No comments:
Post a Comment