gpt4 book ai didi

C# 了解如何向后遍历字符串

转载 作者:太空宇宙 更新时间:2023-11-03 12:18:17 30 4
gpt4 key购买 nike

我正在学习 c# 类(class),它为我提供了一些我可以复制和粘贴的代码,还有一些是我自己编写的。无论如何,我不明白在这个 for() 循环中为什么我们要从 int i = target.Length 属性中减去 1?

static string reverseString(string target)
{
String result = "";

// walk the target string backwards
for (int i = target.Length - 1; i >= 0; i--)
{
// add this letter to the result
result += target[i];
}

// return the result to the calling code
return result;
}

最佳答案

举个例子。

string target = "ABC";
// target can be thought of as an array of characters
// target[0] holds 'A'
// target[1] holds 'B'
// target[2] holds 'C'

int length = target.Length;
// length would be 3 because Length is the count of the chars
// but if you were to try and get the value of target[3] you would get an error
// because target ends at [2] (index 2)

因此您需要从 .Length - 1 开始并向后计算到 0(而不是 1)。

关于C# 了解如何向后遍历字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48758546/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com