我有String
之类的地址"abc 201 lmn road pqr near xyz building state maharashtra navi mumbai, 4212001 .... "
我想将此字符串拆分为
List<string> addrList = new List<string>();
addrList.add("abc 201 lmn road pqr near");
addrList.add("xyz building state maharashtra ");
addrList.add("navi mumbai, 4212001");
我尝试了以下功能
private string[] splitToNChar(string inputString, int chunkSize)
{
List<string> myList = new List<string>();
for (int i = 0; i < inputString.Length; i += chunkSize)
{
myList.Add(inputString.Substring(i, chunkSize));
}
return myList.ToArray();
}
,但是当我以40
个字符的形式传递块大小时,它具有例外,例如
抛出异常:mscorlib.dll中的'System.ArgumentOutOfRangeException' eee例外:索引和长度必须指代 字符串。
答案 0 :(得分:0)
如果inputString
是"abc 201 lmn road pqr near xyz building state maharashtra navi mumbai, 4212001 .... "
扩展功能的结果是:
private string[] splitToNChar(string inputString, int chunkSize)
{
if (chunkSize > inputString.Length)
throw new Exception("input string (" + inputString.Length + ") is smaller than chunksize (" + chunkSize + ")");
List<string> myList = new List<string>();
for (int i = 0; i < inputString.Length; i += chunkSize)
{
if (i + chunkSize < inputString.Length)
myList.Add(inputString.Substring(i, chunkSize));
else
myList.Add(inputString.Substring(i)); //ADD REST OF STRING
}
return myList.ToArray();
}
输出:
[0] abc 201 lmn road pqr near
[1] xyz building state mahar
[2] ashtra navi mumbai, 42120
[3] 01 ....
希望我能正确理解您的问题。