2011-12-02 3 views
1

길이가 긴 문자열이 있는데, 미리 정의 된 단어 개수 후에 줄 바꿈을하고 싶습니다.N 단어 다음에 새 줄을 분할하십시오.

문자열은 정수 및 부동 소수점 단위로, 프로그램에서 사용되는 데이터 타입이지만, 텍스트가 아닌 숫자를 표현하는 데 사용됩니다

내 문자열과 같이합니다. 공백과 숫자를 포함 할 수있는 문자 세트로 구성됩니다.

50 자 뒤의이 줄을 새 줄로 나누고 싶습니다.

+2

단어 또는 문자 수가 스플릿? 어떤거야? – Icarus

+0

@lcarus : 단어로 – Vijjendra

+1

어, 50 자와 50자를 모두 나누면 어떻게 계획 하시겠습니까? 그건 말이 안돼. – mattypiper

답변

4
string text = "A string is a data type used in programming, such as an integer and floating point unit, but is used to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers."; 

int startFrom = 50; 
var index = text.Skip(startFrom) 
       .Select((c, i) => new { Symbol = c, Index = i + startFrom }) 
       .Where(c => c.Symbol == ' ') 
       .Select(c => c.Index) 
       .FirstOrDefault(); 


if (index > 0) 
{ 
    text = text.Remove(index, 1) 
     .Insert(index, Environment.NewLine); 
} 
+0

.NET 3.5 +를 사용할 수있는 사람들을 부러워합니다 ... 그러나 가독성은 매우 어렵습니다. –

+0

가독성에 대해서는 동의하지 않습니다. 아마도 LINQ를 자주 사용하지 않았기 때문에 이것은 이상한 일입니다. – sll

+0

그는 매우 간결한 코드에서 강력한 작업을하기 위해 Linq와 Lambdas를 사용하고 있습니다. 컴파일러와 프레임 워크는 그를 위해 수 많은 작업을 수행하고 있습니다. 당신은이 1337 skillz을 아주 잘 부러워해야합니다. – mattypiper

0

사소, 당신은 쉽게에 대한 간단한에서 50 자 후 이에 대한을 분할을 수행 할 수 있습니다 :

string s = "A string is a data type used in programming, such as an integer and floating point unit, but is used to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers."; 
    List<string> strings = new List<string>(); 
    int len = 50; 
    for (int i = 0; i < s.Length; i += 50) 
    { 
     if (i + 50 > s.Length) 
     { 
      len = s.Length - i; 
     } 
     strings.Add(s.Substring(i,len)); 
    } 

귀하의 결과는 strings에서 개최되고있다.

+0

왜 StringBuilder를 사용하여 .ToString()을 사용할 수 있습니까? –

+0

@ Ryan 그는 형식 문자열로 문자열을 원한다면 'strings.Aggregate ((i, j) => i + Environment.NewLine + j)'라고 할 수 있습니다. –

0
 string thestring = "A string is a data type used in programming, such as an integer and floating point unit, but is used to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers."; 
     string sSplitted = string.Empty; 
     while (thestring.Length > 50) 
     { 
      sSplitted += thestring.Substring(1, 50) + "\n"; 
      thestring = thestring.Substring(50, (thestring.Length-1) -50); 
     } 
     sSplitted += thestring; 
관련 문제