簡體   English   中英

使用 indexOf() 將字符串拆分為多個 int 形式

[英]Splitting a string into multiple int form using indexOf()

這是我的第一篇文章,所以放輕松。 這是一個家庭作業問題,但我花了大約 7 個小時通過各種方式完成這個目標,但沒有成功。 我正在為賦值構建各種方法,我需要弄清楚如何將String拆分為多個int變量。

例如:給定String "100 200 300" 我需要將其更改為三個int 100 , 200 , 300 我必須使用indexOf() ,不能使用split()或數組。

    String scores="100 200 300";
    int n=scores.indexOf(" ");
    String sub=scores.substring(0,n);
    Integer.parseInt(sub);

這讓我得到第一個字符串“100”並解析它。 但是,我不知道如何繼續代碼,所以它會得到下一個。 對於我的方法,我將需要新的int變量作為后面的參數。

編輯:我想我需要使用for循環:類似於:

for(int i=0; i<=scores.length; i++)
{//I do not know what to put here}

你需要兩件事:

  1. 一個循環;
  2. 能夠從它停止的地方運行indexOf() (提示:閱讀Javadoc )。
public static void main(String[] args) {
        String scores = "100 200 300";
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        int n = 0;
        while (n != -1) {
            String sub = "";
            n = scores.indexOf(" ");
            if (n != -1) {
                sub = scores.substring(0, n);
                scores = scores.substring((n + 1));
            } else {
                sub = scores;
            }
            numbers.add(Integer.parseInt(sub));
        }
        for (int i : numbers) {
            System.out.println("" + i);
        }
    }

嘗試這樣的事情來循環並將數字添加到數組列表。 arraylist 數字將包含您的所有數字。

嘗試這個:

    String scores="100 200 300";
    int offset = 0;
    int space;
    int score;

    scores = scores.trim(); //clean the string

    do
    {
        space= scores.indexOf(" ", offset);
        if(space > -1)
        {
            score = Integer.parseInt(scores.substring(offset , space)); 
        }
        else
        {
            score = Integer.parseInt(scores.substring(offset));     
        }

        System.out.println(score);  
        offset = space + 1;

    }while(space > -1);

您的 'n' 變量是重要的部分。 你通過從 0 到 'n' 切片得到你的第一個字符串,所以你的下一個字符串不是從 0 開始,而是從 n + " ".size()

好的,這就是我想出的:由於我需要將新解析的ints與不同的變量進行比較,並確保ints的數量等於不同的變量,因此我創建了這個while循環:

public boolean isValid()
{
int index=0;
int initialindex=0;
int ntotal=0;
int ncount=0;
boolean flag=false;
while (index!=-1)
{
    index=scores.indexOf(" ");
    String temp=scores.substring(initialindex,index);
    int num=Integer.parseInt(temp);
    ntotal+=num;
    ncount++;
    initialindex=index;
}
 if (ntotal==total && ncount==count)
{
    flag=true;
}
return flag;
}

暫無
暫無

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

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