2011-08-10 2 views
4

나는 단어의 목록을 가지고 :특정 문자로 시작하고 끝나는 모든 단어를 반환하는 방법은 무엇입니까? 다음과 같이

List<string> words = new List<string>(); 
words.Add("abet"); 
words.Add("abbots"); //<---Return this 
words.Add("abrupt"); 
words.Add("abduct"); 
words.Add("abnats"); //<--return this. 
words.Add("acmatic"); 
내가 문자로 시작 6 개 문자의 모든 단어를 반환하고 싶습니다

"A"와 결과가 단어를 반환해야 5 편지로 "t"가 "수도원"과 "비정상".

var result = from w in words 
      where w.StartsWith("a") && //where ???? 

다섯 번째 문자를 맞추기 위해 추가해야하는 절은 무엇입니까? 이 작은 단어에 대한 예외를 던질 것이라고 Length 확인없이

where w.StartsWith("a") && w.Length > 5 && w[4] == 't' 

:

+0

답변 해 주셔서 감사합니다. 그러나 제 질문을 약간 수정하고 5 번째와 6 번째 글자가 "ts"인 모든 단어를 반환하고 싶습니다. – Fraiser

답변

7
var result = from w in words 
      where w.Length == 6 && w.StartsWith("a") && w[4] == 't' 
      select w; 
1

당신은 인덱서를 사용할 수 있습니다.

인덱서는 0부터 시작한다는 것을 기억하십시오.

1
// Now return all words of 6 letters that begin with letter "a" and has "t" as 
// the 5th letter. The result should return the words "abbots" and "abnats". 

var result = words.Where(w => 
    // begin with letter 'a' 
    w.StartsWith("a") && 
    // words of 6 letters 
    (w.Length == 6) && 
    // 't' as the 5th letter 
    w[4].Equals('t')); 
1

나는 다음과 같은 코드를 테스트 한 올바른 결과를 주었다, 수정 된 질문에 대한 대답에서

var result = from w in words 
      where w.StartsWith("a") && w.Length == 6 && w.Substring(4, 1) == "t" 
      select w; 
1

를 마지막 두 글자를 확인하려는 경우, 당신은 ENDWITH 방법을 사용할 수 있습니다 확인할 색인을 지정하십시오. SLaks 지적한 바와 같이, 인덱스를 사용하는 경우 길이를 검사하여 작은 단어가 문제를 일으키지 않는지 확인해야합니다.

List<string> words = new List<string>(); 
words.Add("abet"); 
words.Add("abbots"); //<---Return this 
words.Add("abrupt"); 
words.Add("abduct"); 
words.Add("abnats"); //<--return this. 
words.Add("acmatic"); 

var result1 = from word in words 
       where word.Length == 6 && word.StartsWith("a") && word.EndsWith("ts") 
       select word; 

var result2 = from word in words 
       where word.Length == 6 && word.StartsWith("a") && word[4] == 't' && word[5] == 's' 
       select word; 
관련 문제