2017-02-10 2 views
0

문자열을 가져 와서 지정된 구문을 포함하여 내용을 삭제 한 다음 마지막 단어를 반환해야합니다. 이 경우 "추가 정보".특정 단어를 포함하여 문자열의 내용을 삭제하십시오.

기본적으로,이 스크립트 문자열

 "Please visit 

this 
website 
for more information if you have questions" 

을해야하며 (단어 "for"

을 반환 이것은 단지 예입니다 참고 문자열은 아무것도 할 수 있고 나는 줄 바꿈으로 엉망이 만든 의도적으로 그것이 절반의 시간으로 보이기 때문입니다.)

아래의 분할 방법이 작동하지만 마지막 단어를 반환하지만 부분 문자열 방법이 작동하지 않습니다.

내가 뭘 잘못하고 있는지 알기! 이것에

public static string InfoParse(string input) 


{ 
    string extract = input; 


    extract = input.Substring(0, input.IndexOf("more information")); 


    extract = extract.Split(' ').Last(); 

    return extract; 



} 

답변

1

변경 :

public static string InfoParse(string input) 
    { 
     //string extract = input; 
     string extract = input.Substring(0, input.IndexOf("more information")); 
     extract = extract.Split(new string[] {" ", "\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries).Last(); 
     return extract; 
    } 

또는이 코드를 잘못 무엇인지 보여주기 : 귀하의 분할 후 마지막 공간과 마지막 항목 을 반환

public static string InfoParse(string input) { //string extract = input; string extract = input.Substring(0, input.IndexOf(" more information")); extract = extract.Split(' ').Last(); return extract; } 

공간은 정확히 "추가 정보"전에 공간이었습니다 -> 그래서 빈 문자열을 반환합니다

편집 : 이제도에 LINEBREAK

+0

첫 번째는 분명히 더 강력하다 (생각을 자신의 "줄 바꿈 등으로 엉망") 더 나은 중 일치하는 공백에 포함되지 . – dlatikay

+0

맞습니다. 원래 질문 소스의 정확한 문제를 보여주고 싶었습니다. – Pedro

+0

작동하지만 마지막 단어의 일부로 줄 바꿈을 고려하고 있습니다. 마지막 단어를 파싱 할 목적으로 줄 바꿈을 동일하게 처리하는 방법이 있습니까? –

0
당신은으로 RegularExpression 사용할 수 있습니다

:

using System.Text.RegularExpressions; 

string InfoParse(string input, string word) 
{ 
    Match m = Regex.Match(input, @"\s?(?<LastBefore>\w+)\s+" + word, RegexOptions.Singleline); 
    if (m.Success) 
     return m.Groups["LastBefore"].Value; 
    return null; 
} 
관련 문제