替换两个字符串的第一个字符和最后一个字符的任务
问题描述:
我在做练习,它也提供了解决方案,但是没有解释解决方案中的代码,并且无法理解代码。希望我能理解它替换两个字符串的第一个字符和最后一个字符的任务
练习得到的帮助: 写C#程序从给定的字符串,其中第一个和最后一个字符会改变它们的位置创建一个新的字符串。
字符串: w3resource 的Python
预期输出: e3resourcw nythoP
解决方案:
public class Exercise16 {
static void Main(string[] args)
{
Console.WriteLine(first_last("w3resource"));
Console.WriteLine(first_last("Python"));
Console.WriteLine(first_last("x"));
}
public static string first_last(string ustr)
{
// code that I don't understand
return ustr.Length > 1
? ustr.Substring(ustr.Length - 1) + ustr.Substring(1, ustr.Length - 2) + ustr.Substring(0, 1) : ustr;
}
}
PS - 我在C#中,但不是在初学者亲整体拼图
答
在C#中,?
运算符也被称为conditional operator。它的作用就像是一个微缩的if
声明,可让您在单个表达式中表达整个声明。在这种情况下,它用于验证字符串中是否至少有两个字符,否则它将返回单个字符字符串本身。
对于Substring
陈述,考虑哪些正在从ustr
每次调用提取字符...
-
ustr.Substring(ustrLength - 1)
:提取的最后一个字符 -
ustr.Substring(1, ustr.Length - 2)
:提取第二的所有字符到第二持续 -
ustr.Substring(0, 1)
:提取的第一个字符
当按照上述顺序连接时,可以看到生成的字符串将从原始字符串的最后一个字符开始,后面是从第二个到第二个的所有字符,最后是第一个字符。
答
基本上它说,如果长度大于1,则执行这样的:
ustr.Substring(ustr.Length - 1) + ustr.Substring(1, ustr.Length - 2) + ustr.Substring(0, 1)
如果没有,返回该字符串变量:
ustr
这是条件运算"?:"
的示例:Microsoft Docs Conditional Operator.
子串意味着你得到特定范围的字符串字符。例如,你可以检查Substring Examples.
啊我明白了。感谢您一行一行地解释微型'if'语句。很有用 – Zane