2012-09-18 72 views
-3

我們有一個字符串:0000029653。如何以某種價值轉移數字。
例如,移位4然後結果必須是:0296530000 有這樣的操作符或函數嗎?
謝謝將字符串向左移

+1

而當您將示例轉換爲6時應該得到什麼結果? –

+0

@HenkHolterman:結果必須是:6530000029 – user1260827

+1

供參考:這就是所謂的旋轉,而不是移位。 –

回答

0

您可以將您的數字作爲整數轉換爲字符串並返回。

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

Downvote真的嗎? :/ – Owen

4

你可以將其轉換爲一個號碼,然後做到這一點:

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

然後將其轉換回字符串,並墊留下了0

+0

你在編號的開頭是否看到過0000?它不會工作 – Vytalyi

+0

請解釋,我不明白爲什麼這不起作用? –

+0

它不起作用,因爲當你在一個int中存儲一個數字時,開始的0被忽略,因爲它們並不代表什麼。如果我做int num = 00001; num將保持1,而不是00001.這個答案將你的字符串轉換爲一個int(在進行任何數學運算之前,它將失去0的infront)。 – Owen

1
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; 
    } 
+0

沒有必要將複製作爲字符數組 - 字符串中的字符可以通過直接索引字符串來訪問(即'numberStr [ j%i]'會工作)。 – Adam

2

如果你不想使用子串和索引,你也可以用Linq玩:

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

下面的方法用數字n來表示你想要移動/旋轉字符串的次數。如果數字大於字符串的長度,我已將MOD按字符串長度取出。

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

    }