문자열에서 여러 단어를 분리하는 방법 (자바)

Erandall :

내가 파일에서 읽고 있어요 있음을 알 수없는 길이, 문자열에서, 알 수없는 길이, 단어를 얻는 방법을 알아 내기 위해 애 쓰고 있었어요. 문자열에서 내가 원하는 단어는 항상로 구분됩니다 "." 및 / 또는 "&"전체 문자열을 따옴표로 둘러싸여. EX : ".Word.Characters 및 숫자 및 Letters.Typos & 잘못 입력." 나는 각각의 위치를 ​​알고 "." 와 "&"뿐만 아니라 그들은 발생 횟수.

I는 단어로 분리되는지의 여부에 기초하여 배열 실시 예 [I] [J]에 단어를 공급하려면 "." 또는 "&". 단어 사이에 포함 그래서 "." 어레이의 J 행에 "&"가 연결 배열 및 단어의 I 열에 설정된다.

입력 문자열은 단어의 대부분 가변 수를 포함 할 수 있습니다. 관심의 하나의 단어, 또는 백 개 +가있을 수 있다는 것을 의미한다.

나는이 문제를 해결하기 위해 배열을 사용하는 것을 선호 것입니다. 내가 읽은 바로는 정규 표현식은 천천히,하지만 일이 될 것입니다. 분할 () 할 수있다 또한 작업,하지만 난 손 전에보고 어떤 단어를 알고 거라고 생각합니다.

이 문자열에서 ". .Word.Characters & 숫자 & Letters.Typos & 잘못 입력" 내가 얻을 기대 : (이에 대한 걱정없이하는 행 또는 열입니다)

[널] [단어] [널] []

[문자], [번호], [문자],

[오타] [오타] [널]

이 문자열에서 ".Alpha.Beta.Zeta & 페퍼." 내가 얻을 기대 :

[α, 널],

[β, 제로],

[제타] 포닐]

//NumerOfPeriods tells me how many word "sections" are in the string
//Stor[] is an array that holds the string index locations of "."
for(int i=0;i<NumberOfPeriods;i++)
{
    int length = Stor[i];
    while(Line.charAt(length) != '"')
    {
        length++;
    }
    Example[i] = Line.substring(Stor[i], length);
}
//This code can get the words separated by "." but not by "&"

//Stor[] is an array that holds all string index locations of '.'
//AmpStor[] is an array that holds all string index locations of '&'
int TotalLength = Stor[0];
int InnerLength = 0;
int OuterLength = 0;
while(Line.charAt(TotalLength) != '"')
{
    while(Line.charAt(OuterLength)!='.')
    {
        while(Line.charAt(InnerLength)!='&')
        {
            InnerLength++;
        }
        if(Stor[i] > AmpStor[i])
        {
            Example[i][j] = Line.substring(Stor[i], InnerLength);
        }
        if(Stor[i] < AmpStor[i])
        {
            Example[i][j] = Line.substring(AmpStor[i],InnerLength);
        }
            OuterLength++;
    }
}
//Here I run into the issue of indexing into different parts of the array i & j
RgSW :

이것은 내가 (이 코드는 완전히 다르다지만 작동) 문제를 해결할 방법이다.

우선, 따옴표와 선행 및 후행 단어가 아닌 문자를 제거합니다. 이것은 사용하여 수행 할 수 있습니다 replaceAll:

String Formatted = Line.replaceAll( "(^\"[.&]*)|([.&]*\"$)", "" );

첫 번째 인수의 정규 표현식은 종료되고 선행 및 후행 모두에서 따옴표 일치 .의과 &들. 두 번째 인수가 빈 문자열 (이 빈 문자열로 대체) 때문에이 방법은 일치하는 문자가 제거되고 새 문자열을 반환합니다.

지금 당신은 각각이 문자열을 분할 할 수 있습니다 .사용 split방법. 당신은이 호출 한 후 출력 배열을 정의 할 수 있습니다 :

String[] StringGroups = Formatted.split( "\\." );
String[][] Elements = new String[StringGroups.length][];

이스케이프 백 슬래시 (사용 \\이에 분할해야 함을 표시하기 위해 지점 이전) .이 방법은 (단지 정규 표현식에 걸리므로, -characters .비 개행 문자에 분할).

이제 각각이 배열의 각 스트링을 분할 &동일한 사용 split방법. 당신의 직접 결과를 추가 Elements배열 :

// Loop over the array
int MaxLength = 0;
for( int i = 0; i < StringGroups.length; i ++ ) {
   String StrGroup = StringGroups[ i ];
   String[] Group = StrGroup.split( "&" );
   Elements[ i ] = Group;

   // Measure the max length
   if( Group.length > MaxLength ) {
       MaxLength = Group.length;
   }
}

A는 \\이후 입력 필요하지 않습니다 &단지 일치 &-characters합니다. 이제 당신은 단지 배열에 데이터를 입력해야합니다. MaxLength변수는 추가입니다 null배열에 값을. 당신이 그들을 원하지 않는 경우, 단지 그들을 제거하고 여기에 완료됩니다.

당신이 원한다면 null그러나 값을, 당신의 요소 배열을 통해 루프는 새로운 배열로 현재 행을 복사 :

for( int i = 0; i < Elements.length; i ++ ) {
    String[] Current = Elements[ i ];
    String[] New = new String[ MaxLength ];

    // Copy existing values into new array, extra values remain null
    System.arraycopy( Current, 0, New, 0, Current.length );
    Elements[ i ] = New;
}

이제 Elements배열은 당신이 원하는 정확히 들어 있습니다.

여기에 전체 실행 코드는 다음과 같습니다

public class StringSplitterExample {
    public static void main( String[] args ) {
        test( "\".Word.Characters&Numeric&Letters.Typos&Mistypes.\"" );
        System.out.println(); // Line between
        test( "\".Alpha.Beta.Zeta&Iota.\"" );
    }

    public static void test( String Line ) {
        String Formatted = Line.replaceAll( "(^\"[.&]*)|([.&]*\"$)", "" );
        String[] StringGroups = Formatted.split( "\\." );
        String[][] Elements = new String[StringGroups.length][];

        // Loop over the array
        int MaxLength = 0;
        for( int i = 0; i < StringGroups.length; i ++ ) {
            String StrGroup = StringGroups[ i ];
            String[] Group = StrGroup.split( "&" );
            Elements[ i ] = Group;

            // Measure the max length
            if( Group.length > MaxLength ) {
                MaxLength = Group.length;
            }
        }

        for( int i = 0; i < Elements.length; i ++ ) {
            String[] Current = Elements[ i ];
            String[] New = new String[ MaxLength ];

            // Copy existing values into new array, extra values remain null
            System.arraycopy( Current, 0, New, 0, Current.length );
            Elements[ i ] = New;
        }

        for( String[] Group : Elements ) {
            for( String String : Group ) {
                System.out.print( String );
                System.out.print( " " );
            }
            System.out.println();
        }
    }
}

본 실시 예의 출력 :

워드 널 널 
문자 숫자 문자 
오타 잘못 입력 널 

알파 널 
베타 널 
제타 제타

이 작품 그래서, 당신은 심지어 위치를 알 필요가 없습니다 .&문자가 문자열에 있습니다. 자바는 단지 당신을 위해 그렇게 할 것입니다.

추천

출처http://43.154.161.224:23101/article/api/json?id=208511&siteId=1