string str = "Programmatic"; char[] str2 = str.ToCharArray(); char[] str3 = new char[str2.Length]; int j = 0; for (int i = 0; i < str2.Length; i++) { str3[i] = str2[str2.Length - i - 1]; } foreach (char ele in str3) { Console.Write(ele); }
时间: 2024-03-20 17:41:15 浏览: 18
这段代码的作用是将字符串 "Programmatic" 反转并输出。
这段代码可以用 Array.Reverse 方法来简化:
```csharp
string str = "Programmatic";
char[] str2 = str.ToCharArray();
Array.Reverse(str2);
Console.WriteLine(new string(str2));
```
这里使用了 ToCharArray 方法将字符串转换为字符数组,然后使用 Array.Reverse 方法将字符数组反转,最后使用 new string(char[]) 构造函数将字符数组转换为字符串并输出。
相关问题
优化代码 string str = "Programmatic Python"; char[] str2 = str.ToCharArray(); List<char> newStr = new List<char>(); for (int i = 0; i < str2.Length; i++) { for (int j = 1 + i; j < str2.Length; j++) { if (str2[i] == str2[j]) { newStr.Add(str2[i]); } } } foreach (char item in newStr) { Console.WriteLine(item); }
这段代码的作用是找出字符串 "Programmatic Python" 中重复出现的字符,并输出这些字符。
首先,这段代码可以使用 HashSet<char> 来简化,HashSet 会自动去重:
```csharp
string str = "Programmatic Python";
HashSet<char> newStr = new HashSet<char>();
for (int i = 0; i < str.Length; i++) {
for (int j = i + 1; j < str.Length; j++) {
if (str[i] == str[j]) {
newStr.Add(str[i]);
}
}
}
foreach (char item in newStr) {
Console.WriteLine(item);
}
```
此外,我们还可以使用 LINQ 来进一步简化:
```csharp
string str = "Programmatic Python";
var newStr = str.Where((c, i) => str.Substring(i + 1).Contains(c)).Distinct();
foreach (var item in newStr) {
Console.WriteLine(item);
}
```
这里使用了 Where 方法来筛选出符合条件的字符,使用 Substring 方法来截取字符串,使用 Contains 方法来判断字符是否存在于截取后的字符串中,最后使用 Distinct 方法去重。
PowerShell.Application
PowerShell.Application is a COM object that allows developers to interact with PowerShell in a programmatic way. It provides a set of methods and properties for running PowerShell commands, scripts, and modules from within a Windows application. This object can be used to automate tasks, manage systems, and perform administrative tasks through PowerShell. It is available in Windows PowerShell and PowerShell Core on Windows, macOS, and Linux.