HOW TO:使用基本字串作業執行字串操作

下列範例會使用基本字串作業主題中所討論到的一些方法,以一種可能在實際應用程式中發現的方式,來建構可執行字串操作的類別。 MailToData 類別會將個人的姓名和地址儲存在不同的屬性中,並允許您將 City、State 和 Zip 欄位組合成單一字串,以便顯示給使用者看。 此外,類別也可讓使用者將城市、省/市和郵遞區號當成單一字串來輸入;應用程式會自動剖析這個單一字串,然後將正確的資訊輸入對應的屬性中。

為了簡單起見,這個範例會使用具有命令列介面的主控台應用程式。

範例

Imports System
Imports System.IO

Class MainClass

    Public Shared Sub Main()
        Dim MyData As New MailToData()

        Console.Write("Enter Your Name:")
        MyData.Name = Console.ReadLine()
        Console.Write("Enter Your Address:")
        MyData.Address = Console.ReadLine()
        Console.Write("Enter Your City, State, and ZIP Code separated by spaces:")
        MyData.CityStateZip = Console.ReadLine()


        Console.WriteLine("Name: {0}", MyData.Name)
        Console.WriteLine("Address: {0}", MyData.Address)
        Console.WriteLine("City: {0}", MyData.City)
        Console.WriteLine("State: {0}", MyData.State)
        Console.WriteLine("ZIP Code: {0}", MyData.Zip)

        Console.WriteLine("The following address will be used:")

        Console.WriteLine(MyData.Address)
        Console.WriteLine(MyData.CityStateZip)
    End Sub
End Class


Public Class MailToData
    Private strName As String = " "
    Private strAddress As String = " "
    Private strCityStateZip As String = " "
    Private strCity As String = " "
    Private strState As String = " "
    Private strZip As String = " "

    Public Sub New()

    End Sub

    Public Property Name() As String
        Get
            Return strName
        End Get
       Set
            strName = value
        End Set
    End Property 

    Public Property Address() As String
        Get
            Return strAddress
        End Get
        Set
            strAddress = value
        End Set
    End Property 

    Public Property CityStateZip() As String
        Get
            Return ReturnCityStateZip()
        End Get
        Set
            strCityStateZip = value
            ParseCityStateZip()
        End Set
    End Property

    Public Property City() As String
        Get
            Return strCity
        End Get
        Set
            strCity = value
        End Set
    End Property 

    Public Property State() As String
        Get
            Return strState
        End Get
        Set
            strState = value
        End Set
    End Property 

    Public Property Zip() As String
        Get
            Return strZip
        End Get
        Set
            strZip = value
        End Set
    End Property

    Private Sub ParseCityStateZip()
        Dim CityIndex As Integer
        Dim StateIndex As Integer
        ' Check for an exception if the user did not enter spaces between
        ' the elements.

        Try

        ' Find index position of the space between
        ' city and state and assign that value to CityIndex.
        CityIndex = strCityStateZip.IndexOf(" ")

        ' Initialize the CityArray to the value of the 
        ' index position of of the first white space.
        Dim CityArray(CityIndex) As Char

        ' Copy the city to the CityArray.
        strCityStateZip.CopyTo(0, CityArray, 0, CityIndex)

        ' Find index position of the space between
        ' state and zip and assign that value to CityIndex.
        StateIndex = strCityStateZip.LastIndexOf(" ")

        ' Initialize the StateArray to the length of the state.
        Dim StateArray(StateIndex - CityIndex) As Char

        ' Copy the state to the StateArray.
        strCityStateZip.CopyTo(CityIndex, StateArray, 0, StateIndex - CityIndex)

        ' Initialize the ZipArray to the length of the zip.
        Dim ZipArray(strCityStateZip.Length - StateIndex) As Char

        ' Copy the zip to the ZipArray.
        strCityStateZip.CopyTo(StateIndex, ZipArray, 0, strCityStateZip.Length - StateIndex)

        ' Assign city to the value of CityArray.
        strCity = New String(CityArray)

        ' Trim white spaces, commas, and so on.
        strCity = strCity.Trim(New Char() {" "c, ","c, ";"c, "-"c, ":"c})

        ' Assign state to the value of StateArray.
        strState = New String(StateArray)

        ' Trim white spaces, commas, and so on.
        strState = strState.Trim(New Char() {" "c, ","c, ";"c, "-"c, ":"c})


        ' Assign zip to the value of ZipArray.
        strZip = New String(ZipArray)

        ' Trim white spaces, commas, and so on.
        strZip = strZip.Trim(New Char() {" "c, ","c, ";"c, "-"c, ":"c})

        ' If an exception is encountered, alert the user to enter spaces
        ' between the elements.

        Catch OverflowException As Exception
                Console.WriteLine(ControlChars.Lf + ControlChars.Lf + "You must enter spaces between elements." + ControlChars.Lf + ControlChars.Lf)  
        End Try

    End Sub

    Private Function ReturnCityStateZip() As String
        ' Make state uppercase.
        strState = strState.ToUpper()

        ' Put the value of city, state, and zip together in the proper manner.
        Dim MyCityStateZip As String = String.Concat(strCity, ", ", strState, " ", strZip)

        Return MyCityStateZip
    End Function
End Class
using System;

class MainClass
{
    static void Main(string[] args)
    {
        MailToData MyData = new MailToData();

        Console.Write("Enter Your Name:");
        MyData.Name = Console.ReadLine();
        Console.Write("Enter Your Address:");
        MyData.Address = Console.ReadLine();
        Console.Write("Enter Your City, State, and ZIP Code separated by spaces:");
        MyData.CityStateZip = Console.ReadLine();


        Console.WriteLine("Name: {0}", MyData.Name);
        Console.WriteLine("Address: {0}", MyData.Address);
        Console.WriteLine("City: {0}", MyData.City);
        Console.WriteLine("State: {0}", MyData.State);
        Console.WriteLine("Zip: {0}", MyData.Zip);

        Console.WriteLine("The following address will be used:");

        Console.WriteLine(MyData.Address);
        Console.WriteLine(MyData.CityStateZip);
    }
}

public class MailToData
{
    string   name = " ";
    string   address = " "; 
    string  citystatezip = " ";
    string   city = " "; 
    string   state = " "; 
    string   zip = " ";

    public MailToData()
    {
    }

    public string Name
    {
        get{return name;}
        set{name = value;}
    }

    public string Address
    {
        get{return address;}
        set{address = value;}
    }

    public string CityStateZip
    {
        get
        {
            return ReturnCityStateZip();
        }
        set
        {
            citystatezip = value;
            ParseCityStateZip();
        }
    }


    public string City
    {
        get{return city;}
        set{city = value;}
    }

    public string State
    {
        get{return state;}
        set{state = value;}
    }

    public string Zip
   {
        get{return zip;}
        set{zip = value;}
    }

    private void ParseCityStateZip()
    {  
        int CityIndex; 
        int StateIndex;
        // Check for an exception if the user did not enter spaces between
        // the elements.
        try
        {

            // Find index position of the space between
            // city and state and assign that value to CityIndex.
            CityIndex = citystatezip.IndexOf(" ");

            // Initialize the CityArray to the value of the 
            // index position of the first white space.
            char[] CityArray = new char[CityIndex];

            // Copy the city to the CityArray.
            citystatezip.CopyTo(0,CityArray ,0, CityIndex);

            // Find index position of the space between
            // state and zip and assign that value to CityIndex.
            StateIndex = citystatezip.LastIndexOf(" ");

            // Initialize the StateArray to the length of the state.
            char[] StateArray = new char[StateIndex - CityIndex];

            // Copy the state to the StateArray.
            citystatezip.CopyTo(CityIndex, StateArray, 0, (StateIndex - CityIndex));

            // Initialize the ZipArray to the length of the zip.
            char[] ZipArray = new char[citystatezip.Length - StateIndex];

            // Copy the zip to the ZipArray.
            citystatezip.CopyTo(StateIndex, ZipArray, 0, (citystatezip.Length - StateIndex));

            // Assign city to the value of CityArray.
            city = new String(CityArray);

            // Trim white spaces, commas, and so on.
            city = city.Trim(new char[]{' ', ',', ';', '-', ':'}); 

            // Assign state to the value of StateArray.
            state = new String(StateArray);

            // Trim white spaces, commas, and so on.
            state = state.Trim(new char[]{' ', ',', ';', '-', ':'});


            // Assign zip to the value of ZipArray.
            zip = new String(ZipArray);

            // Trim white spaces, commas, and so on.
            zip = zip.Trim(new char[]{' ', ',', ';', '-', ':'});
        }
        // If an exception is encountered, alert the user to enter spaces
        // between the elements.
        catch(OverflowException)
        {
            Console.WriteLine("\n\nYou must enter spaces between elements.\n\n");
        } 
    }

    private string ReturnCityStateZip()
    {
        // Make state uppercase.
        state = state.ToUpper();

        // Put the value of city, state, and zip together in the proper manner.
        string MyCityStateZip = String.Concat(city, ", ", state, " ", zip);

        return MyCityStateZip;
    }
}
using namespace System;

public ref class MailToData
{
private:
    String^ name;
    String^ address;
    String^ citystatezip;
    String^ city;
    String^ state;
    String^ zip;

public:
    MailToData()
    {
        name = " ";
        address = " ";
        citystatezip = " ";
        city = " ";
        state = " ";
        zip = " ";
    }

    property String^ Name
    {
        String^ get() {return name;}
        void set(String^ value) {name = value;}
    }

    property String^ Address
    {
        String^ get() {return address;}
        void set(String^ value) {address = value;}
    }

    property String^ CityStateZip
    {
        String^ get()
        {
            return ReturnCityStateZip();
        }
        void set(String^ value)
        {
            citystatezip = value;
            ParseCityStateZip();
        }
    }

    property String^ City
    {
        String^ get(){return city;}
        void set(String^ value) {city = value;}
    }

    property String^ State
    {
        String^ get(){return state;}
        void set(String^ value) {state = value;}
    }

    property String^ Zip
    {
        String^ get(){return zip;}
        void set(String^ value) {zip = value;}
    }

private:
    void ParseCityStateZip()
    {
        int CityIndex;
        int StateIndex;
        // Check for an exception if the user did not enter spaces between
        // the elements.
        try
        {

            // Find index position of the space between
            // city and state and assign that value to CityIndex.
            CityIndex = citystatezip->IndexOf(" ");

            // Initialize the CityArray to the value of the
            // index position of the first white space.
            array<Char>^ CityArray = gcnew array<Char>(CityIndex);

            // Copy the city to the CityArray.
            citystatezip->CopyTo(0, CityArray, 0, CityIndex);

            // Find index position of the space between
            // state and zip and assign that value to CityIndex.
            StateIndex = citystatezip->LastIndexOf(" ");

            // Initialize the StateArray to the length of the state.
            array<Char>^ StateArray = gcnew array<Char>(StateIndex - CityIndex);

            // Copy the state to the StateArray.
            citystatezip->CopyTo(CityIndex, StateArray, 0, (StateIndex - CityIndex));

            // Initialize the ZipArray to the length of the zip.
            array<Char>^ ZipArray = gcnew array<Char>(citystatezip->Length - StateIndex);

            // Copy the zip to the ZipArray.
            citystatezip->CopyTo(StateIndex, ZipArray, 0, (citystatezip->Length - StateIndex));

            // Assign city to the value of CityArray.
            city = gcnew String(CityArray);

            // Trim white spaces, commas, and so on.
            city = city->Trim(gcnew array<Char>{' ', ',', ';', '-', ':'});

            // Assign state to the value of StateArray.
            state = gcnew String(StateArray);

            // Trim white spaces, commas, and so on.
            state = state->Trim(gcnew array<Char>{' ', ',', ';', '-', ':'});


            // Assign zip to the value of ZipArray.
            zip = gcnew String(ZipArray);

            // Trim white spaces, commas, and so on.
            zip = zip->Trim(gcnew array<Char>{' ', ',', ';', '-', ':'});
        }
        // If an exception is encountered, alert the user to enter spaces
        // between the elements.
        catch (OverflowException^)
        {
            Console::WriteLine("\n\nYou must enter spaces between elements.\n\n");
        }
    }

    String^ ReturnCityStateZip()
    {
        // Make state uppercase.
        state = state->ToUpper();

        // Put the value of city, state, and zip together in the proper manner.
        String^ MyCityStateZip = String::Concat(city, ", ", state, " ", zip);

        return MyCityStateZip;
    }
};

ref class MainClass
{
public:
    static void Main()
    {
        MailToData^ MyData = gcnew MailToData();

        Console::Write("Enter Your Name:");
        MyData->Name = Console::ReadLine();
        Console::Write("Enter Your Address:");
        MyData->Address = Console::ReadLine();
        Console::Write("Enter Your City, State, and ZIP Code separated by spaces:");
        MyData->CityStateZip = Console::ReadLine();


        Console::WriteLine("Name: {0}", MyData->Name);
        Console::WriteLine("Address: {0}", MyData->Address);
        Console::WriteLine("City: {0}", MyData->City);
        Console::WriteLine("State: {0}", MyData->State);
        Console::WriteLine("Zip: {0}", MyData->Zip);

        Console::WriteLine("The following address will be used:");

        Console::WriteLine(MyData->Address);
        Console::WriteLine(MyData->CityStateZip);
    }
};

int main()
{
    MainClass::Main();
}

執行上述程式碼時,會要求使用者輸入自己的姓名和地址。 應用程式會將這項資訊放入適當的屬性中,並建立出顯示城市、省/市和郵遞區號資訊的單一字串,將資訊重新顯示給使用者看。

請參閱

其他資源

基本字串作業