2012-09-18 2 views
-3

우리는 문자열이 0000029653입니다. 어떤 값으로 숫자를 이동하는 법.
예를 들어, 4 시프트 한 후 결과는 다음과 같아야합니다. 0296530000 이 연산자 또는 함수가 있습니까?
감사합니다.문자열을 왼쪽으로 시프트

+1

예를 6으로 이동하면 결과가 어떻게됩니까? –

+0

@HenkHolterman : 그 결과는 다음과 같아야합니다 : 6530000029 – user1260827

+1

FYI : 그것은 회전이 아니라 이동이라고합니다. –

답변

0

숫자를 int로 캐스팅하여 문자열로 되돌릴 수 있습니다. 당신은 숫자로 변환 할 수

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

Downvote 정말요? :/ – Owen

4

다음을 수행하십시오

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

는 0 왼쪽 문자열과 패드로 다시 변환

+0

숫자의 시작 부분에 0000을 보았습니까? 그것은 작동하지 않습니다 – Vytalyi

+0

pls 설명, 왜이 작동하지 않을 거라 생각하지 않아? –

+0

int에 숫자를 저장할 때 시작 0은 아무 의미도 없기 때문에 무시됩니다. 내가 int num = 00001; num은 00001이 아니라 1을 유지합니다.이 대답은 문자열을 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))); 

    } 
관련 문제