簡體   English   中英

如何使字符串成為字符串數組?

[英]How do I make a string a string array?

我想要做的是將這樣的東西: "The Three Pigs"轉換成這樣的數組:

Array[0]="The"
Array[1]="Three"
Array[2]="Pigs"

字符串類沒有一個方法,我不知道如何自己做拆分似乎不適合我的目的。 示例代碼:

import java.util.Scanner;


public class Main {

/**
 * @param args
 */
public static void main(String[] args) {
    GetNumber();
}

private static void GetNumber() {
    System.out.println("Enter your words.");
    Scanner S=new Scanner(System.in);
    String O=S.next();
    String[] A=O.split(" ");
    for(int Y=0;A.length>Y;Y++){
        System.out.println(A[Y]);
    }
}

}

此代碼將輸出 The if i put in The Little Pigs

String text = "The Three Pigs";
String[] array = text.split(" ");

編輯:

如果您想讓用戶輸入一行文本而不是單個單詞,請使用:

String O = S.nextLine();

代替:

String O = S.next();

您可以使用 split 方法如下

String[] arrString = s.split(" ");

請參閱 String 類上的 split 方法

String[] theArray = "The Three Pigs".split(" ");

至於您更新的問題,請將您的掃描儀從.next()更改為.nextLine()

import java.util.Scanner;

public class ArrayTest
{
    public static void main( String[] args )
    {
        System.out.println( "Enter your words." );
        Scanner scanner = new Scanner( System.in );
        String O = scanner.nextLine();
        System.out.println( O );
        String[] A = O.split( " " );
        for ( int Y = 0 ; A.length > Y ; Y++ )
        {
            System.out.println( A[ Y ] );
        }
    }
}

事實上,該String確實有一個方法

/編輯
Scanner#next返回輸入的下一個標記。 Scanner s 用空格標記它們接收到的輸入,因此"The Little Pigs"將通過調用next標記為"The""Little""Pigs" 如果您想要整行,請嘗試Scanner#nextLine

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM