我希望这不是一个愚蠢的问题,因为这只是我进入JAVA和Android编程的第五周。所以我对此仍然很陌生。
这是我的代码:
public void splitData(){ //**********************PROBLEM HERE**********************
//Initialise everything to 0 to prepare for variable entry
y=0;
gender = "";
sAge = "";
sTotalC = "";
smoker = "";
sHDLC = "";
medication = "";
sSystolic = "";
//To locate the spaces in the data
for(x=0;x<toSplit.length();x++){
if (toSplit.charAt(x) == ' '){
spaceCount[y]=x;
y++;
}
}
//to put together gender
for(x=0;x<spaceCount[0];x++){
gender+= toSplit.charAt(x);
}
//to put together age
for(x=spaceCount[0]+1;x<spaceCount[1];x++){
sAge+=toSplit.charAt(x);
}
//to put together total Cholesterol
for(x=spaceCount[1]+1;x<spaceCount[2];x++){
sTotalC+=toSplit.charAt(x);
}
//to put together smoker status
for(x=spaceCount[2]+1;x<spaceCount[3];x++){
smoker+=toSplit.charAt(x);
}
//to put together HDL Cholesterol level
for(x=spaceCount[3]+1;x<spaceCount[4];x++){
sHDLC+=toSplit.charAt(x);
}
//to put together medication status
for(x=spaceCount[4]+1;x<spaceCount[5];x++){
medication+=toSplit.charAt(x);
}
//to put together Systolic BP
for(x=spaceCount[5]+1;x<=toSplit.length();x++){
sSystolic+=toSplit.charAt(x);
}
}
}
那么基本上我的可怕尝试是找到字符串中的所有空格,并根据空格,将字符串中的字母组合成不同的变量,并将每个新构造的单词显示为EditText。
此代码中的所有内容都很好,直到我按下按钮mSplit应该开始执行所述任务,然后它会显示“很遗憾应用程序已停止工作”。
我用Google搜索并在许多网站上捅了我的鼻子,但大多数人使用其他形式的方法来分割他们的句子并立即显示它,而不将其保存到另一个数组或变量中。
看起来并且我知道我可能以漫长而愚蠢的方式做这件事,因为我对C ++知之甚少,因此我试图以我知道的唯一方式来做这件事。
我对所有建议和意见持开放态度,我提前谦卑地感谢你。
答案 0 :(得分:3)
使用split函数然后将其放入字符串数组
String what = "word word1 word2 word3";
String [] temp = what.split(" ");
temp [0]将包含“word” temp [1]将包含“word1” 等等...
答案 1 :(得分:0)
试试这段代码:
String[] infoArray = info.split("\\s+");
为你的地址做同样的事情
这样,您不必在知道数组之前初始化数组,也可以忽略所有空格。在分割之前,最好trim
你的字符串。
答案 2 :(得分:0)
如果你知道它们中有多少并且中间有多个空间......
String toSplit = "aoksd oaskod ssdoks aoskdo skasdk soakd";
String[] msg = new String[6];
int a = 0;
int c = 0;
while(true)
{
a = toSplit.indexOf(" ");
if(a == -1)
{
msg[c] = toSplit;
break;
}
msg[c++] = toSplit.substring(0, a);
toSplit = toSplit.substring(a, toSplit.length()).trim();
}