我想在foreach数组的最后一项中添加某些字符串。
该程序完美无缺。给定“pending”数组中的项目,它应该将out值附加到挂起值的最后一项:
String a = out + "-" + rptdate + "-";
for (String pn : pending) {
//checks if total value + pending length value is less than 160
if (a.length() + pn.length() < 160) { // < to leave room for the comma as well
if (a.length() != 0) {
if (a.length() != 14) {
a += ",";
}
}
a += pn;
} else {
resultingStrings.add(a);
a = pn;
Log.d("messages", a);
}
}
resultingStrings.add(a);
for (String r : resultingStrings) {
sendSMS(r);
}
答案 0 :(得分:1)
尝试简单的代码
int size = pending.size();
int index = 0;
for (String pn : pending) {
if(index == size - 1){
// it is last foreach => add your last string here
}
index++;
...
}
希望这个帮助
答案 1 :(得分:1)
你也可以这样做,
for(int i = 0; i < array.length; i++) {
if(i = (array.length - 1)) {
//this is the last element in the array
}
}
答案 2 :(得分:1)
如果你需要做的就是抓住Collection的最后一个元素并为它添加一些文本,那么这应该可行。
String out = "Some value";
int lastIndex = pending.getSize() -1; // < 0 indexed
String lastItem = pending.get(lastIndex)
String newLastItem = lastItem + out; // < String concatenation
但是从你的片段我不认为这是你的追求,因为如果我们删除一些神奇的数字并纠正缩进,并对你试图做什么做出一些假设
String a = out + "-" + rptdate + "-";
int prefixLength = a.length();
for (String pn : pending) {
//checks if total value + pending length value is less than 160
if (a.length() + pn.length() < MAX_LENGTH) { // < to leave room for the comma as well
if (a.length() > prefixLength) {
a += ",";
}
a += pn;
} else {
// have string longer than max length, so save and start a new sms.
resultingStrings.add(a);
Log.d("messages", a); // < log a before you overwrite it.
a = pn;
}
}
// DO YOU WANT TO APPEND out AS A SUFFIX TO a HERE ???
// a += out;
// but if so youll want to consider the case if a is now > MAX_LENGTH
resultingStrings.add(a); // add the last string
// send all composed strings
for (String r : resultingStrings) {
sendSMS(r);
}
我正在挑选你相对较新的编码,所以我建议你首先从一些伪代码开始,然后在你的代码中成为注释。始终保持代码格式良好,以便匹配缩进,并为变量和常量使用描述性名称。