繁体   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