使用indexOf()将字符串拆分为多个int形式 [英] Splitting a string into multiple int form using indexOf()

查看:247
本文介绍了使用indexOf()将字符串拆分为多个int形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一篇文章,所以对我很轻松。这是一个家庭作业问题,但我花了大约7个小时通过各种方式来完成这个目标并且没有成功。我正在为赋值构建各种方法,我需要弄清楚如何将 String 拆分为几个 int 变量。

This is my first post so go easy on me. This IS a homework question, but I have spent about 7 hours working through various means to complete this goal and have had no success. I am building various methods for an assignment, and I need to figure out how to split a String into several int variables.

例如:给定字符串100 200 300我需要将其更改为3 int 100 200 300 。我必须使用 indexOf(),并且不能使用 split()或数组。

Ex: given the String "100 200 300" I need to change it to three int of 100, 200, 300. I have to use indexOf(), and cannot use split() or arrays.

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

这让我得到第一个字符串100并解析它。但是,我不知道如何继续代码,所以它将获得下一个。对于我的方法,我将需要新的 int 变量用于以后的参数。

This lets me get the first string "100" and parse it. However, I do not know how to continue the code so it will get the next ones. For my method, I will need the new int variables for later arguments.

编辑:我想我需要使用进行循环:类似于:

I think I need to use a for loop: something like:

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


推荐答案

Joe,indexOf()超载,看看这个版本:

Joe, indexOf() is overloaded, check out this version:

http://docs.oracle.com/javase /7/docs/api/java/lang/String.html#indexOf(int,%20int)

这篇关于使用indexOf()将字符串拆分为多个int形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆