2016-11-12 1 views
2

문자열에서 char을 제거하려고합니다. 문자열에있는 해당 char의 모든 요소는 아닙니다. 예. "|red|red|red|red|""red|red|red|red"으로 바꾸고 싶습니다. 그래서 문자열의 첫 번째와 마지막 색인이 특정 문자인지 확인한 다음 해당 문자를 제거하는 함수를 만들고 싶습니다.F # 특정 문자열 인덱스의 char 제거/바꾸기

지금까지 나는 이런 식으로 뭔가 함께 올라와있다 :

let rec inputFormatter (s : string) : string = 
    match s.[1] with 
    |'|'|','|'.'|'-' -> // something that replaces the char with "" in the string s 
         (inputFormatter s) 
    |_ -> match s.[(String.length s)] with 
      |"|"|","|"."|"-" -> // same as above. 
           (inputFormatter s) 
     |_ -> s 

사람이 날 난 내 기능을 쓸 수 있는지 알아내는 데 도움이 수 있습니까? 물론 더 많은 평범함을 발견한다면 당신은 또한 영리하게 다른 기능을 제안 할 수 있습니다.

미리 감사드립니다. 사용

+1

문자열 인스턴스의 기존 "'.Replace'' 메소드를 사용하지 않는 이유는 무엇입니까? – Gustavo

+0

문자열에있는 char의 모든 요소를 ​​제거하기 때문에? 만약 내가 s.InReplace ("|", "") 문자열에있는 모든 파이프를 제거합니다 – Nulle

+5

결합 [string.IndexOf] (https://msdn.microsoft.com/en-us/library/kwb0bwyd (v = .110) .aspx), [string.LastIndexOf] (https://msdn.microsoft.com/en-us/library/0w96zd3d(v=vs.110) .aspx)와 [string.Remove] (https://msdn.microsoft.com/en-us/library/d8d7z2kk(v=vs.110).aspx). –

답변

4
let replace elem (str:string) =  
    let len = String.length str 
    if str.[0] = elem && str.[len-1] = elem then str.[1..len-2] 
    else str 

: 마크는 더 나은 옵션을 제안한 것처럼

는 다시입니다

let replace elem (str:string) =  
    let lens = String.length str 
    let lene = String.length elem  
    if lene <= lens && str.[0..lene-1] = elem && str.[lens-lene..lens-1] = elem then str.[lene..lens-lene-1] 
    else str 

UPDATE : 여기

replace '|' "|red|red|red|red|" 

// val it : string = "red|red|red|red" 

그리고 대신 문자의 문자열로 작업 버전입니다 를 사용하여 Trim

let replace (elem:string) (str:string) = str.Trim(elem.ToCharArray()) 
+0

대단히 감사합니다 !!!!! – Nulle

+3

[string.Trim] (https://msdn.microsoft.com/en-us/library/d4tt83f9(v=vs.110) .aspx)을 사용하지 않는 이유는 무엇입니까? –

0

나는 Gutavo의 수정을 사용하지 않았지만 그 사람이 내 자신의 기능을 고취하게 만들었다.

let rec theButcher (s : string) : string = 
    match s.[0] with 
    |'|'|','|'.'|'-'|' ' -> (theButcher s.[1..]) 
    |_ -> match s.[(String.length s)-1] with 
      |'|'|','|'.'|'-'|' ' -> (theButcher s.[0..((String.length s)-2)]) 
      |_ -> s