分割地址需要帮助

时间:2014-07-22 21:44:33

标签: c# asp.net

我想将以下地址分成两行:

ABCD E FGHI JKLMNOP QRSTU VWXYz Apt NUMBER1234 Block A

字符0-30到第1行

字符31-结束第二行

如果第30个字符位于我希望将整个单词推到第二行的单词之间。在上面的地址中,第30个字符位于单词“VWXYZ”之间,所以我想将它移动到第2行,如下所示。

最终结果应该是这样的:

第1行:ABCD E FGHI JKLMNOP QRSTU

第2行:VWXYz Apt NUMBER1234 A座

if(address.length > 30)                                                                                               
{
  string add = address.Tostring();
  string arraystring[] = add.split(" ");      
}

2 个答案:

答案 0 :(得分:0)

这假设超过30的任何东西进入下一行。即使长度为65个字符。检查以确保它长于30,然后从30向后检查,直到找到第一个空格。

        string message = "ABCD E FGHI JKLMNOP QRSTU VWXYz Apt NUMBER1234 Block A";
        string firstline = message;
        string secondline="";
        if(message.Length > 30)
        {
            for(int i = 30; i > 0;)
            {
                if(message[i] == ' ')
                {
                    firstline = message.Substring(0, i);
                    secondline = message.Substring(i + 1);
                    break;
                }
                else
                {
                    i--;
                }
            }
        }

答案 1 :(得分:-3)

这是一种非常简单,非常快速的方法,无需LINQ或Regex。

    public string[] SplitLine(string line, int numberOfCharacters)
    {
        if (line.Length < numberOfCharacters)
            return new [] { line }; // no splitting necessary

        string[] result = new string[2]; // only two lines needed

        int splitPoint = numberOfCharacters; // the position to split at if it is a white space

        // if it is not a white space, iterate the splitPoint down until you reach a white space character
        while (splitPoint >= 0 && line[splitPoint] != ' ')
            splitPoint--;

        //return the two lines
        result[0] = line.Substring(0, splitPoint);
        result[1] = line.Substring(splitPoint, line.Length - splitPoint);
        return result;
    }