设置结束参数时c#子字符串方法错误

标签 c# string exception substring

我正在尝试从字符串本身中提取部分字符串。我从 http 请求中获取字符串。我想从位置 17 切片到其 Length - 3。这是我的 c# 代码:

var response = await responseURI2.Content.ReadAsStringAsync();
Debug.WriteLine(response);
Debug.WriteLine(response.GetType());
Debug.WriteLine(response.Length);
int length = (response.Length) - 3;
Debug.WriteLine(length);
try{
    var zero = response.Substring(17, length);
    Debug.WriteLine(zero);
}
catch
{
    Debug.WriteLine("Not able to do substring");
}

这是输出:

[0:] "dshdshdshdwweiiwikwkwkwk..."
[0:] System.String
[0:] 117969
[0:] 117966
[0:] Not able to do substring

关于为什么它不能正确执行 Substring 有什么想法吗?如果我只做response.Substring(17),它就可以工作。但是,当我尝试从末尾剪切时,失败了。

最佳答案

当使用索引时,例如,您想获取从第17位置到从末尾开始第3d的子字符串,您可以使用范围而不是子字符串:

var zero = response[17..^3];

如果您坚持使用子字符串,则必须手动进行算术运算:

var zero = response.Substring(17, response.Length - 17 - 3);

关于设置结束参数时c#子字符串方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73567565/

相关文章:

c# - 自动使列适合垂直滚动条的 ListView

c# - 在 metroapp 中显示存储在存储文件中的图片

php - 在变量中添加空格

c# - 从字符串中获取总数 'objects'

c# - 从属性构造函数中抛出异常

java - 使用 fragment 在 Android 构造函数中设置 View

c# - SortedList/SortedDictionary 奇怪的行为

c# - 声明字符串 public static readonly 与 public const 与 public static const

c# - 序列不包含匹配元素

C# - 编译器错误