วิธีการแปลงสตริงเป็นบูล


90

ฉันมีstringที่สามารถเป็น "0" หรือ "1" และรับประกันได้ว่าจะไม่เป็นอย่างอื่น

คำถามก็คือวิธีที่ดีที่สุดง่ายที่สุดและสง่างามที่สุดในการแปลงเป็น a boolคืออะไร?


3
หากมีค่าที่ไม่คาดคิดอยู่ในอินพุตให้พิจารณาใช้ TryParse ( stackoverflow.com/questions/18329001/… )
Michael Freidgeim

คำตอบ:



81

ไม่สนใจความต้องการเฉพาะของคำถามนี้และในขณะที่ไม่ควรส่งสตริงไปที่บูลวิธีหนึ่งก็คือการใช้เมธอด ToBoolean ()ในคลาส Convert:

bool val = Convert.ToBoolean("true");

หรือวิธีการขยายเพื่อทำแผนที่แปลก ๆ ที่คุณกำลังทำอยู่:

public static class StringExtensions
{
    public static bool ToBoolean(this string value)
    {
        switch (value.ToLower())
        {
            case  "true":
                return true;
            case "t":
                return true;
            case "1":
                return true;
            case "0":
                return false;
            case "false":
                return false;
            case "f":
                return false;
            default:
                throw new InvalidCastException("You can't cast that value to a bool!");
        }
    }
}

1
พฤติกรรมของ
Convert ToBoolean

1
รู้สึกBoolean.TryParseเป็นที่นิยมมากเมื่อค่าต้องมีการแปลงเป็นมันไม่โยนFormatExceptionเหมือนConvert.ToBoolean
user3613932

49

ฉันรู้ว่านี่ไม่ได้ตอบคำถามของคุณ แต่เพียงเพื่อช่วยเหลือคนอื่น หากคุณกำลังพยายามแปลงสตริง "จริง" หรือ "เท็จ" เป็นบูลีน:

ลองใช้ Boolean.Parse

bool val = Boolean.Parse("true"); ==> true
bool val = Boolean.Parse("True"); ==> true
bool val = Boolean.Parse("TRUE"); ==> true
bool val = Boolean.Parse("False"); ==> false
bool val = Boolean.Parse("1"); ==> Exception!
bool val = Boolean.Parse("diffstring"); ==> Exception!

จำเป็นสำหรับสคริปต์ Powershell ที่อ่านข้อมูล XML และสมบูรณ์แบบ!
Alternatex

20
bool b = str.Equals("1")? true : false;

หรือดีกว่านั้นตามที่แนะนำในความคิดเห็นด้านล่าง:

bool b = str.Equals("1");

39
ฉันพิจารณาอะไรก็ได้ในรูปแบบที่x ? true : falseน่าขบขัน
Kendall Frey

5
bool b = str.Equals("1") ทำงานได้ดีและใช้งานง่ายมากขึ้นในตอนแรก
Erik Philips

@ErikPhilips ไม่เข้าใจง่ายนักเมื่อ String ของคุณstrเป็น Null และคุณต้องการให้ Null แก้ไขเป็น False
MikeTeeVee

8

ฉันทำบางสิ่งที่ขยายได้มากขึ้นเล็กน้อย Piggybacking ตามแนวคิดของ Mohammad Sepahvand:

    public static bool ToBoolean(this string s)
    {
        string[] trueStrings = { "1", "y" , "yes" , "true" };
        string[] falseStrings = { "0", "n", "no", "false" };


        if (trueStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return true;
        if (falseStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return false;

        throw new InvalidCastException("only the following are supported for converting strings to boolean: " 
            + string.Join(",", trueStrings)
            + " and "
            + string.Join(",", falseStrings));
    }

5

ฉันใช้โค้ดด้านล่างเพื่อแปลงสตริงเป็นบูลีน

Convert.ToBoolean(Convert.ToInt32(myString));

ไม่จำเป็นที่จะต้องเรียก Convert ToInt32 หากความเป็นไปได้เพียงสองอย่างคือ "1" และ "0" หากคุณต้องการพิจารณากรณีอื่น ๆ var isTrue = Convert ToBoolean ("true") == true && Convert ToBoolean ("1"); // เป็นเรื่องจริงทั้งคู่.
TamusJRoyce

ดู Mohammad Sepahvand ตอบความคิดเห็นของ Michael Freidgeim!
TamusJRoyce

3

นี่คือความพยายามของฉันในการแปลงสตริงที่ให้อภัยมากที่สุดเพื่อบูลที่ยังคงมีประโยชน์โดยพื้นฐานแล้วจะเน้นเฉพาะอักขระตัวแรกเท่านั้น

public static class StringHelpers
{
    /// <summary>
    /// Convert string to boolean, in a forgiving way.
    /// </summary>
    /// <param name="stringVal">String that should either be "True", "False", "Yes", "No", "T", "F", "Y", "N", "1", "0"</param>
    /// <returns>If the trimmed string is any of the legal values that can be construed as "true", it returns true; False otherwise;</returns>
    public static bool ToBoolFuzzy(this string stringVal)
    {
        string normalizedString = (stringVal?.Trim() ?? "false").ToLowerInvariant();
        bool result = (normalizedString.StartsWith("y") 
            || normalizedString.StartsWith("t")
            || normalizedString.StartsWith("1"));
        return result;
    }
}


1

ฉันใช้สิ่งนี้:

public static bool ToBoolean(this string input)
        {
            //Account for a string that does not need to be processed
            if (string.IsNullOrEmpty(input))
                return false;

            return (input.Trim().ToLower() == "true") || (input.Trim() == "1");
        }

0

ฉันชอบวิธีการขยายและนี่คือวิธีที่ฉันใช้ ...

static class StringHelpers
{
    public static bool ToBoolean(this String input, out bool output)
    {
        //Set the default return value
        output = false;

        //Account for a string that does not need to be processed
        if (input == null || input.Length < 1)
            return false;

        if ((input.Trim().ToLower() == "true") || (input.Trim() == "1"))
            output = true;
        else if ((input.Trim().ToLower() == "false") || (input.Trim() == "0"))
            output = false;
        else
            return false;

        //Return success
        return true;
    }
}

จากนั้นจะใช้มันก็ทำอย่าง ...

bool b;
bool myValue;
data = "1";
if (!data.ToBoolean(out b))
  throw new InvalidCastException("Could not cast to bool value from data '" + data + "'.");
else
  myValue = b;  //myValue is True

-1

หากคุณต้องการทดสอบว่าสตริงเป็นบูลีนที่ถูกต้องโดยไม่มีข้อยกเว้นใด ๆ ให้ลองทำสิ่งนี้:

    string stringToBool1 = "true";
    string stringToBool2 = "1";
    bool value1;
    if(bool.TryParse(stringToBool1, out value1))
    {
        MessageBox.Show(stringToBool1 + " is Boolean");
    }
    else
    {
        MessageBox.Show(stringToBool1 + " is not Boolean");
    }

เอาต์พุตis Boolean และเอาต์พุตสำหรับ stringToBool2 คือ 'ไม่ใช่บูลีน'

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.