在C#中移动字符串

本文关键字:字符串 移动 | 更新日期: 2023-09-27 18:00:55

  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;
  }

我需要将字符串向左移动一个空格,所以我最终得到字符串:"BCDEFGHA"所以我想把字符串改成一个char数组,然后从那里开始工作,但我不确定如何成功地实现这一点。我很确定我需要一个for循环,但我需要一些关于如何将char序列向左移动一个空格的帮助。

在C#中移动字符串

这个怎么样?

public static string ShiftString(string t)
{
    return t.Substring(1, t.Length - 1) + t.Substring(0, 1); 
} 

你可以试试这个:

s = s.Remove(0, 1) + s.Substring(0, 1);

作为一种扩展方法:

public static class MyExtensions
{
    public static string Shift(this string s, int count)
    {
        return s.Remove(0, count) + s.Substring(0, count);
    }
}

然后你可以使用:

s = s.Shift(1);

解决这类关于移位n位置的问题的算法是复制字符串,连接在一起并获得子字符串。(n<长度(字符串((

string s = "ABCDEFGH";
string ss = s + s; // "ABCDEFGHABCDEFGH"

如果你想转移n的位置,你可以进行

var result = ss.Substring(n, s.length);

在C#8及以上版本中

向右旋转一个。。。

t = myString[^1] + myString[..^1];

或者,向左旋转一个。。。

t = myString[1..] + myString[0];

或者,向右旋转一个量。。。

t = myString[^amount..] + myString[..^amount];

或者,向左旋转一个量。。。

t = myString[amount..] + myString[..amount];

就我个人而言,我会这样做:

public static string ShiftString(string t){
    string firstLetter = t.Substring(0, 1);
    return t.Substring(1) + firstLetter;
}

您可以利用stringIEnumerable<char>:这一事实

public static string ShiftString(string t){
    return new String(t.Skip(1).Concat(t).Take(t.Length).ToArray());
}

使用Span<T>我们可以显著提高性能。例如:

public static class StringExtensions
{
    public static string ShiftString(this string s)
    {
        return string.Concat(s.AsSpan(1), s.AsSpan(0, 1));
    }
}

基准

此答案+现有答案。使用跨度,字符串的移位变得更快,并且产生更少的垃圾。

|  Method |     Data |     Mean |   Median | Allocated |
|-------- |--------- |---------:|---------:|----------:|
|    L33t | ABCDEFGH | 18.56 ns | 18.21 ns |      40 B |
|  Zs2020 | ABCDEFGH | 36.04 ns | 35.20 ns |      96 B |
| JohnWoo | ABCDEFGH | 47.69 ns | 47.39 ns |     104 B |
|  AlinaB | ABCDEFGH | 52.56 ns | 52.07 ns |     104 B |

完整测试代码

using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Diagnostics.Windows;
using BenchmarkDotNet.Running;
namespace ConsoleApp10
{
    class Program
    {
        static void Main(string[] args)
        {
            var summary = BenchmarkRunner.Run<StringShiftTest>();
        }
    }
    [Config(typeof(Config))]
    public class StringShiftTest
    {
        private class Config : ManualConfig
        {
            public Config() => AddDiagnoser(MemoryDiagnoser.Default, new EtwProfiler());
        }
        [Params("ABCDEFGH")]
        public string Data;
        [Benchmark]
        public string L33t() => string.Concat(Data.AsSpan(1), Data.AsSpan(0, 1));
        [Benchmark]
        public string Zs2020() => (Data + Data).Substring(1, Data.Length);
        [Benchmark]
        public string JohnWoo() => Data.Substring(1, Data.Length - 1) + Data.Substring(0, 1);
        [Benchmark]
        public string AlinaB() => Data.Remove(0, 1) + Data.Substring(0, 1);
    }
}

StringBuilder类为您提供了更好的性能

static string ShiftString(string str)
{
    if (str == null) throw new ArgumentNullException();
    int strLen = str.Length;
    if (strLen == 0) return string.Empty;
    StringBuilder sb = new StringBuilder(strLen);
    sb.Append(str, 1, strLen - 1);
    sb.Append(str[0]);
    return sb.ToString();
}

下面的方法取数字n,这个数字告诉您要移位/旋转字符串的次数。如果数字大于字符串的长度,我就用字符串的长度来计算MOD。

public static void Rotate(ref string str, int n)
    {
        //if the rotation/shift number is less than or =0 throw exception
        if (n < 1)
            throw new Exception("Negative number for rotation"); 
        //if the String is less than 1 character no need to shift
        if (str.Length < 1) throw new Exception("0 length string");
        if (n > str.Length) // If number is greater than the length of the string then take MOD of the number
        {
            n = n % str.Length;
        }
        StringBuilder s1=new StringBuilder(str.Substring(n,(str.Length - n)));
        s1.Append(str.Substring(0,n));
        str=s1.ToString();

    }

///您可以使用字符串操作的Skip和Take功能

 public static void Rotate1(ref string str, int n)
    {
        if (n < 1)
            throw new Exception("Negative number for rotation"); ;
        if (str.Length < 1) throw new Exception("0 length string");
        if (n > str.Length)
        {
            n = n % str.Length;
        }
        str = String.Concat(str.Skip(n).Concat(str.Take(n)));
    }

您也可以通过一个简单的LINQ语句来实现这一点:

注意:同样可以通过简单的for和/或while循环实现

string a = "ABCDEFGH";  
a = new string(Enumerable.Range(0, a.Length).Select(i => (a[(i+1)%a.Length])).ToArray());

C#8.0

private static string ShiftString(string t, int shift)
{
    if (shift < 0)//left
    {
        shift = -shift;
        return t[shift..] + t[..shift];
    }
    else//right
    {
        return t[(t.Length - shift)..] + t[..(t.Length - shift)];
    }
}