programing

의 줄바꿈으로 문자열을 분할합니다.그물

css3 2023. 4. 10. 22:08

의 줄바꿈으로 문자열을 분할합니다.그물

에서 문자열을 새 행으로 분할해야 합니다.NET 및 문자열을 분할하는 방법은 Split 메서드뿐입니다.하지만 그렇게 하면 새로운 선으로 쉽게 분할할 수 없습니다.그러면 어떻게 하면 좋을까요?

문자열로 분할하려면 문자열 배열을 사용하는 오버로드를 사용해야 합니다.

string[] lines = theText.Split(
    new string[] { Environment.NewLine },
    StringSplitOptions.None
);

편집:
텍스트에서 다른 유형의 줄 바꿈을 처리하는 경우 여러 문자열을 일치시키는 기능을 사용할 수 있습니다.이렇게 하면 줄 바꿈 유형 중 하나가 올바르게 분할되어 텍스트의 빈 줄과 공백이 유지됩니다.

string[] lines = theText.Split(
    new string[] { "\r\n", "\r", "\n" },
    StringSplitOptions.None
);

를 사용하는 것은 어떻습니까?

using (System.IO.StringReader reader = new System.IO.StringReader(input)) {
    string line = reader.ReadLine();
}

문자열 사용은 피하도록 하세요.일반적인 솔루션에서는 분할할 수 있습니다.기능을 사용하는 모든 장소에서 메모리 내의 원래 문자열과 분할 복사본이 더 많이 사용되기 때문입니다.100MB 문서를 처리하는 32비트 일괄 처리 앱을 실행하면 8개의 동시 스레드로 처리됩니다.전에 가 본 적은 없지만...

대신 이와 같은 반복기를 사용하십시오.

public static IEnumerable<string> SplitToLines(this string input)
{
    if (input == null)
    {
        yield break;
    }

    using (System.IO.StringReader reader = new System.IO.StringReader(input))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

이것에 의해, 데이터에 대해서 보다 메모리 효율이 높은 루프를 실시할 수 있습니다.

foreach(var line in document.SplitToLines()) 
{
    // one line at a time...
}

물론 모든 것을 기억하려면 이 작업을 수행할 수 있습니다.

var allTheLines = document.SplitToLines().ToArray();

다음과 같이 문자열을 쉽게 분할할 수 있습니다.

aString.Split(Environment.NewLine.ToCharArray());

Guffa의 답변을 바탕으로 확장 클래스에서 다음을 사용합니다.

public static string[] Lines(this string source) {
    return source.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
}

Regex도 옵션입니다.

    private string[] SplitStringByLineFeed(string inpString)
    {
        string[] locResult = Regex.Split(inpString, "[\r\n]+");
        return locResult;
    }

문자열 변수의 경우s:

s.Split(new string[]{Environment.NewLine},StringSplitOptions.None)

이는 사용자 환경의 회선 끝 정의를 사용합니다.Windows 에서는, 행엔딩은 CR-LF(캐리지 리턴, 행 피드) 또는 C# 의 이스케이프 문자입니다.\r\n.

이것은 신뢰할 수 있는 솔루션입니다.와 행을 재결합하면 원래 문자열과 같기 때문입니다.

var lines = s.Split(new string[]{Environment.NewLine},StringSplitOptions.None);
var reconstituted = String.Join(Environment.NewLine,lines);
Debug.Assert(s==reconstituted);

하지 말아야 할 일:

  • 를 사용합니다.이는 빈 행이 구문적인 목적을 갖는 마크다운 등의 마크업이 해제되기 때문입니다.
  • 구분자로 분할new char[]{Environment.NewLine}Windows 에서는, 새로운 행 마다 1개의 빈 문자열 요소가 작성되기 때문입니다.

이 질문의 다른 해답은 재사용 가능한 코드 분류에 속하지 않고 편리하지 않기 때문에 2비트를 추가하려고 합니다.

다음 코드 블록이 확장됩니다.string오브젝트를 지정하여 스트링 작업 시 자연스러운 방법으로 사용할 수 있습니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.ObjectModel;

namespace System
{
    public static class StringExtensions
    {
        public static string[] Split(this string s, string delimiter, StringSplitOptions options = StringSplitOptions.None)
        {
            return s.Split(new string[] { delimiter }, options);
        }
    }
}

해서 '어울리다'를 할 수 되었습니다..Split()임의의 문자열에서 다음과 같이 기능합니다.

string[] result;

// Pass a string, and the delimiter
result = string.Split("My simple string", " ");

// Split an existing string by delimiter only
string foo = "my - string - i - want - split";
result = foo.Split("-");

// You can even pass the split options parameter. When omitted it is
// set to StringSplitOptions.None
result = foo.Split("-", StringSplitOptions.RemoveEmptyEntries);

문자로 ."\n" ★★★★★★★★★★★★★★★★★」"\r\n"딜리미터 파라미터로 지정합니다.

코멘트: 마이크로소프트가 이 과부하를 구현한다면 좋을 것이다.

로부터 시작합니다.NET 6 새로운 String을 사용할 수 있습니다.크로스 플랫폼 회선 엔딩을 정규화하기 위한 ReplaceLineEndings() 메서드는 현재 가장 간단한 방법입니다.

var lines = input
  .ReplaceLineEndings()
  .Split(Environment.NewLine, StringSplitOptions.None);

현재 VB에서 이 기능(다른 답변 기준)을 사용하고 있습니다.네트워크:

Private Shared Function SplitLines(text As String) As String()
    Return text.Split({Environment.NewLine, vbCrLf, vbLf}, StringSplitOptions.None)
End Function

먼저 플랫폼 로컬뉴라인으로 분할을 시도한 후 가능한 각뉴라인으로 폴백합니다.

만약 , 나는 이것을 만들 이다.Public유틸리티 클래스로 옮기거나 확장 방법으로 만들 수도 있습니다.

회선을 백업하는 방법은 다음과 같습니다.

Private Shared Function JoinLines(lines As IEnumerable(Of String)) As String
    Return String.Join(Environment.NewLine, lines)
End Function

음, 실제로 분할하면 다음과 같습니다.

//Constructing string...
StringBuilder sb = new StringBuilder();
sb.AppendLine("first line");
sb.AppendLine("second line");
sb.AppendLine("third line");
string s = sb.ToString();
Console.WriteLine(s);

//Splitting multiline string into separate lines
string[] splitted = s.Split(new string[] {System.Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);

// Output (separate lines)
for( int i = 0; i < splitted.Count(); i++ )
{
    Console.WriteLine("{0}: {1}", i, splitted[i]);
}
string[] lines = text.Split(
  Environment.NewLine.ToCharArray(), 
  StringSplitOptions.RemoveEmptyStrings);

[ Remove Empty Strings ]옵션은 \r 뒤에 \n이 있기 때문에 빈 엔트리가 없는 것을 확인합니다.

(댓글을 반영하기 위해 편집:) 텍스트 내의 실제 빈 행도 폐기됩니다.이것은 보통 제가 원하는 것이지만, 당신의 요구는 아닐 수도 있습니다.

나는 환경에 대해 몰랐다.뉴라인, 하지만 이게 아주 좋은 해결책인 것 같아.

제 시도는 다음과 같습니다.

        string str = "Test Me\r\nTest Me\nTest Me";
        var splitted = str.Split('\n').Select(s => s.Trim()).ToArray();

추가.Trim은 아직 존재할 수 있는 \r 또는 \n을 삭제합니다(예를 들어 Windows에서 문자열이 os x newline 문자로 분할되는 경우).하지만 가장 빠른 방법은 아닐 겁니다.

편집:

코멘트가 올바르게 지적하고 있듯이, 행의 선두 또는 새로운 행의 피드 전에 공백이 없어집니다.이 공백을 유지해야 하는 경우 다른 옵션 중 하나를 사용합니다.

여기의 예는 훌륭하고, 보다 읽기 쉬운 방법으로 RSA 키를 분할하는 현재의 "과제"에 도움이 되었습니다.Steve Coopers 솔루션 기반:

    string Splitstring(string txt, int n = 120, string AddBefore = "", string AddAfterExtra = "")
    {
        //Spit each string into a n-line length list of strings
        var Lines = Enumerable.Range(0, txt.Length / n).Select(i => txt.Substring(i * n, n)).ToList();
        
        //Check if there are any characters left after split, if so add the rest
        if(txt.Length > ((txt.Length / n)*n) )
            Lines.Add(txt.Substring((txt.Length/n)*n));

        //Create return text, with extras
        string txtReturn = "";
        foreach (string Line in Lines)
            txtReturn += AddBefore + Line + AddAfterExtra +  Environment.NewLine;
        return txtReturn;
    }

RSA-key를 33자 폭과 따옴표로 표시하는 것은 간단합니다.

Console.WriteLine(Splitstring(RSAPubKey, 33, "\"", "\""));

출력:

Splitstring()의 출력;

누군가 유용하게 쓰였으면 좋겠는데...

바보 같은 대답: 오래된 파일을 사용할 수 있도록 임시 파일에 씁니다.

var s = "Hello\r\nWorld";
var path = Path.GetTempFileName();
using (var writer = new StreamWriter(path))
{
    writer.Write(s);
}
var lines = File.ReadLines(path);
using System.IO;

string textToSplit;

if (textToSplit != null)
{
    List<string> lines = new List<string>();
    using (StringReader reader = new StringReader(textToSplit))
    {
        for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
        {
            lines.Add(line);
        }
    }
}

사실 아주 쉬워요.

VB.NET:

Private Function SplitOnNewLine(input as String) As String
    Return input.Split(Environment.NewLine)
End Function

C#:

string splitOnNewLine(string input)
{
    return input.split(environment.newline);
}

언급URL : https://stackoverflow.com/questions/1547476/split-a-string-on-newlines-in-net