use*_*751 10 c# arrays string char shift
static void Main(string[] args)
{
string s = "ABCDEFGH";
string newS = ShiftString(s);
Console.WriteLine(newS);
}
public static string ShiftString(string t)
{
char[] c = t.ToCharArray();
char save = c[0];
for (int i = 0; i < c.Length; i++)
{
if (c[i] != c[0])
c[i] = c[i - 1];
}
Console.WriteLine(c);
String s = new string(c);
return s;
}
Run Code Online (Sandbox Code Playgroud)
我需要将字符串s向左移动一个空格,所以我最终得到了字符串:"BCDEFGHA"所以我想将字符串更改为char数组并从那里开始工作,但我不知道如何成功制作这项工作.我很确定我需要一个for循环,但我需要一些帮助来解决如何将char序列向左移动一个空格.
Joh*_*Woo 10
这个怎么样?
public static string ShiftString(string t)
{
return t.Substring(1, t.Length - 1) + t.Substring(0, 1);
}
Run Code Online (Sandbox Code Playgroud)
你可以试试这个:
s = s.Remove(0, 1) + s.Substring(0, 1);
Run Code Online (Sandbox Code Playgroud)
作为扩展方法:
public static class MyExtensions
{
public static string Shift(this string s, int count)
{
return s.Remove(0, count) + s.Substring(0, count);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用:
s = s.Shift(1);
Run Code Online (Sandbox Code Playgroud)
解决移位n位置这类问题的算法是复制字符串,连接在一起并得到子字符串.(n <长度(字符串))
string s = "ABCDEFGH";
string ss = s + s; // "ABCDEFGHABCDEFGH"
Run Code Online (Sandbox Code Playgroud)
如果你想转移n位置,你可以做到
var result = ss.Substring(n, s.length);
Run Code Online (Sandbox Code Playgroud)
在 C# 8 及更高版本中...
向右旋转一位...
t = myString[^1] + myString[..^1];
Run Code Online (Sandbox Code Playgroud)
或者,向左旋转一位...
t = myString[1..] + myString[0];
Run Code Online (Sandbox Code Playgroud)
或者,向右旋转一定量...
t = myString[^amount..] + myString[..^amount];
Run Code Online (Sandbox Code Playgroud)
或者,向左旋转一定量...
t = myString[amount..] + myString[..amount];
Run Code Online (Sandbox Code Playgroud)