如何使用 C# 逐字反转给定的字符串而不是字母?
创建一个方法reverseWords,该方法将char数组作为输入,并为每个字符反转单词,直到未达到空格为止。在最后一步,将整个字符串从长度0反转为n-1长度。在第一步中,字符串“这是我的书”将变成“koobymsisiht”。在第二步结束时,字符串单词将被反转为“bookmyisThis”
时间复杂度-O(N)
示例
using System;
namespace ConsoleApplication{
public class Arrays{
static void reverse(char[] str, int start, int end){
char temp;
while (start <= end){
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
public char[] reverseWords(char[] s){
int start = 0;
for (int end = 0; end < s.Length; end++){
if (s[end] == ' '){
reverse(s, start, end);
start = end + 1;
}
}
reverse(s, 0,s.Length- 1);
return s;
}
}
class Program{
static void Main(string[] args){
Arrays a = new Arrays();
string s = " 这是我的书 ";
var res = a.reverseWords(s.ToCharArray());
Console.WriteLine(new String(res));
Console.ReadLine();
}
}
}输出结果book my is This
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下