2011-11-16 70 views
-2

串我有數字的隨機串
(號碼只能使用一次,只能從1-9,幾乎任何長度(分1,最多9)):麻煩與在Delphi

var 
Input: String; 
begin 
Input := '431829576'; //User inputs random numbers 

現在我需要獲得指定的號碼前。如何5

var 
Number: Integer; 
begin 
Number := 5; 

並且功能執行結果543182976

我沒有任何想法如何使這樣的功能,謝謝。

+0

那麼你會怎麼做來解決你的問題,它是如何來錯誤的結果? – Kromster

+0

@Krom,顯然 - 將問題發佈到stuckoverflaw :) –

+0

爲什麼我的問題是downvoted? –

回答

9

你的意思是這樣嗎?

function ForceDigitInFront(const S: string; const Digit: Char): string; 
begin 
    result := Digit + StringReplace(S, Digit, '', []); 
end; 

一個更簡單的解決方案是

function ForceDigitInFront(const S: string; const Digit: Char): string; 
var 
    i: Integer; 
begin 
    result := S; 
    for i := 1 to Length(S) do 
    if result[i] = Digit then 
    begin 
     Delete(result, i, 1); 
     break; 
    end; 
    result := Digit + result; 
end; 
+0

常量對象不能作爲var參數傳遞'Delete(result,i,1); ' –

+0

嘿@Andreas!在第一個功能中將'S'更改爲'Digit'。我會接受你的回答。 –

+0

@羅伯茨:抱歉,錯字! –

4

你可以這樣來做:

function ForceDigitInFront(const S: string; const Digit: Char): string; 
var 
    dPos : Integer; 
begin 
    Result := s; 
    dPos := Pos(Digit,S); 
    if (dPos <> 0) then begin // Only apply Digit in front if Digit exists !? 
    Delete(Result,dPos,1); 
    Result := Digit + Result; 
    end; 
end; 

如果數字是不是在輸入字符串,數字是不加入,但變化這個如果不符合你的實現。

2

這裏是減少了所需的字符串分配的NUMER,以及檢查數字已經在前面的解決方案:

function ForceDigitInFront(const S: string; const Digit: Char): string; 
var 
    dPos : Integer; 
begin 
    Result := s; 
    for dPos := 1 to Length(Result) do 
    begin 
    if Result[dPos] = Digit then 
    begin 
     if dPos > 1 then 
     begin 
     UniqueString(Result); 
     Move(Result[1], Result[2], (dPos-1) * SizeOf(Char)); 
     Result[1] := Digit; 
     end; 
     Exit; 
    end; 
    end; 
end;