我們有一個字符串:0000029653
。如何以某種價值轉移數字。
例如,移位4然後結果必須是:0296530000
有這樣的操作符或函數嗎?
謝謝將字符串向左移
Q
將字符串向左移
-3
A
回答
0
您可以將您的數字作爲整數轉換爲字符串並返回。
String number = "0000029653";
String shiftedNumber = number.Substring(4);
+0
Downvote真的嗎? :/ – Owen
4
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)));
}
相關問題
- 1. 你能幫我做這個算法「將字符串向右或向左移動」
- 2. 重命名文件在PowerShell中移動字符串向左或向右字符
- 3. css向左移動一個字符串兩個空格
- 4. 將一個字節向左移2?
- 5. 將字符串從右到左移動到一個字符串中
- 6. 向左移位運算符
- 7. HQL字符串左
- 8. 如何在Bash中以'x'字符向右或向左移動?
- 9. 從字符串向前移動字符串
- 10. 左右移動字符
- 11. UITextView向左增加字符
- 12. .htaccess將文字左移
- 13. 左移和右移字符(ASCII值)。
- 14. jQuery向左移動
- 15. 左連接字符串
- 16. 將char數組從左向右移動
- 17. 字符串將第一個單詞移至字符串末尾
- 18. 當我在當前字符串的左上角時,將文本光標移動到上一個字符串
- 19. 將查詢字符串重定向到非查詢字符串?
- 20. C++將字符串放入字符串向量結構
- 21. 轉移字符串
- 22. Rails將日期遷移到字符串?
- 23. 在python中打印一個字符串,左對齊偏移量
- 24. 將緩衝區移到左側,在LED面板上滾動字符串?
- 25. 反向字符串?
- 26. 反向字符串
- 27. 反向字符串
- 28. 將slf4j重定向到字符串
- 29. 將字符串重定向到scala.sys.process
- 30. 如何從右向左分割字符串,如Python的rsplit()?
而當您將示例轉換爲6時應該得到什麼結果? –
@HenkHolterman:結果必須是:6530000029 – user1260827
供參考:這就是所謂的旋轉,而不是移位。 –