C# 索引和长度必须引用字符串中的位置

C# 索引和长度必须引用字符串中的位置,c#,string,C#,String,我有一些这样的地址 122/852印度拉贾斯坦邦斋浦尔曼斯罗瓦尔学会 我需要写一个函数来提取Mansrovar society,我尝试了下面的代码,但出现了错误 string BuildingAddress = txtAddress.Substring(0, txtAddress.IndexOf(',')); BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' '), Buildin

我有一些这样的地址

122/852印度拉贾斯坦邦斋浦尔曼斯罗瓦尔学会

我需要写一个函数来提取Mansrovar society,我尝试了下面的代码,但出现了错误

 string BuildingAddress = txtAddress.Substring(0, txtAddress.IndexOf(','));
            BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' '), BuildingAddress.Length);

String.Substring
接受两个参数:
start
length
。您正在使用它,就好像第二个是
end
。不是

BuildingAddress =
    BuildingAddress.Substring(BuildingAddress.IndexOf(' '),
                              BuildingAddress.Length - BuildingAddress.IndexOf(' '));

String.Substring
接受两个参数:
start
length
。您正在使用它,就好像第二个是
end
。不是

BuildingAddress =
    BuildingAddress.Substring(BuildingAddress.IndexOf(' '),
                              BuildingAddress.Length - BuildingAddress.IndexOf(' '));
的第二个参数是所需子字符串的长度-所以

BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' '),
                                            BuildingAddress.Length);
仅当
IndexOf
返回0时才有效

如果您只想“从第一个空格开始”,可以将重载与单个参数一起使用:

BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' '));
请注意,如果字符串不包含空格,则仍然会失败-如果有效,它将有一个前导空格。您可能需要:

BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' ') + 1);
它将始终有效,并跳过前导空格-尽管它只跳过一个空格。

的第二个参数是所需子字符串的长度-因此

BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' '),
                                            BuildingAddress.Length);
仅当
IndexOf
返回0时才有效

如果您只想“从第一个空格开始”,可以将重载与单个参数一起使用:

BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' '));
请注意,如果字符串不包含空格,则仍然会失败-如果有效,它将有一个前导空格。您可能需要:

BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' ') + 1);
它将始终有效,并跳过前导空格-尽管它只跳过一个空格