拆分方法将地址划分为街道,城市,州和邮政编码,并仅显示街道和城市段

时间:2015-01-27 07:14:12

标签: c# string-split

这就是我所要求的: 使用拆分方法将地址划分为街道,城市,州和邮政编码,并仅显示街道和城市段

我的错误是什么? 地址格式:123 ABC Dr,Omaha,NE 12345 这是我的代码:(它只显示街道号码)。

/*Address code now*/
            Console.Write("\n\nWhat's your university address:");
            string strUAAaddress = (Console.ReadLine());


            /*divide the address into street, city, state, and zip code. display only the street/city*/
            strUAAaddress=strUAAaddress.Trim();
           if (strUAAaddress.StartsWith(" "))
                strUAAaddress = strUAAaddress.Remove(0, 1); 
          string[] addressParts = strUAAaddress.Split(' '); //strUAAaddress.Split(' ');
          string street = addressParts[0];
          string state = addressParts[2];
          string city = addressParts[1];
          string zipCode = addressParts[3];

          Console.WriteLine(street); Console.Write(city); Console.Write(zipCode); Console.Write(state);

1 个答案:

答案 0 :(得分:2)

查看地址格式,分隔符为,和空格字符。可以尝试以下代码

strUAAaddress=strUAAaddress.Trim();

string[] addressParts = strUAAaddress.Split(',');

string street = addressParts[0];
string city = addressParts[1];
string stateZip = addressParts[2];

这里我们得到街道,城市以及州和邮政编码的组合。 stateZip包含州和邮政编码,我们需要根据空格字符分隔符进一步拆分。

string []data = stateZip.Split(' ');
string state = stateZip[0];
string zip = stateZip[1];