C# 向左移动字符串

C# 向左移动字符串,c#,C#,我们有一个字符串:0000029653。如何按某个值移动数字。 例如,按4移位,则结果必须为:0296530000 是否有用于此的运算符或函数? 谢谢您可以将数字转换为整数到字符串或返回 String number = "0000029653"; String shiftedNumber = number.Substring(4); 您可以将其转换为数字,然后执行以下操作: Result = yournumber * Math.Pow(10, shiftleftby); 然后将其转换回字符串

我们有一个字符串:0000029653。如何按某个值移动数字。 例如,按4移位,则结果必须为:0296530000 是否有用于此的运算符或函数?
谢谢

您可以将数字转换为整数到字符串或返回

String number = "0000029653";
String shiftedNumber = number.Substring(4);

您可以将其转换为数字,然后执行以下操作:

Result = yournumber * Math.Pow(10, shiftleftby);

然后将其转换回字符串并用0s左键填充。如果不想使用子字符串和索引,也可以使用Linq:

    public string Shift(string numberStr, int shiftVal)
    {
        string result = string.Empty;

        int i = numberStr.Length;
        char[] ch = numberStr.ToCharArray();
        for (int j = shiftVal; result.Length < i; j++)
            result += ch[j % i];

        return result;
    }
string inString = "0000029653";
var result = String.Concat(inString.Skip(4).Concat(inString.Take(4)));

下面的方法使用数字n,它告诉您要移动/旋转字符串多少次。如果数字大于字符串的长度,则我已按字符串的长度取模

public static void Rotate(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) // 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();


    }

///You can make a use of Skip and Take functions of the String operations
     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)));

    }

当你将示例移位6时,结果应该是什么?@HenkHolterman:结果必须是:6530000029FYI:这称为旋转,而不是移位。“6530000029”看起来更像是7的旋转。不需要复制为字符数组-字符串中的字符可以通过直接索引字符串来访问,即numberStr[j%i]你在数字开头看到0000了吗?它将不起作用它将不起作用,因为当您在int中存储数字时,起始0将被忽略,因为它们没有任何意义。如果我做int num=00001;num将保存1,而不是00001。此答案将字符串强制转换为int,这将在执行任何数学操作之前丢失前面的0。是的,这就是为什么我建议将它们放回原处,将其向左填充至全宽