初学java,写个从一个字符串中提取偶数位字符组成新的字符(多多指教)

snakenian 2012-09-16 08:42:48
//
public class StringTest {
public static void main(String[] args) {
String str = "abcdefghijk";
String newstr = getStr(str);
System.out.println(newstr);
}

//
static String getStr(String s) {
String newStr = new String();

//get length of string
int temp = s.length();
if(temp % 2 == 0) {
for(int i = 1; i <= (temp - 1); i += 2) {

//rebuild string
newStr += s.charAt(i);
}
}
else {
for(int i = 1; i <= (temp - 2); i += 2) {

//rebuild string
newStr += s.charAt(i);
}
}

return newStr;
}
}
...全文
971 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
walkman_22 2012-09-19
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 的回复:]
偶数位应该是从索引1开始吧(第二位)。


引用 6 楼 的回复:
Java code


public static void main(String[] args) throws Exception {
String s = "asdfbdfasfdsa";
char[] chars = s.toCharArray();
StringBuffer sb = new Stri……
[/Quote]

楼上观察的仔细,确实是这样。
菖蒲老先生 2012-09-17
  • 打赏
  • 举报
回复
if(temp % 2 == 0) {

这个判断没有意义,只要step为2的累加就可以了,
i < temp反正不会越界的。。。
xiars123 2012-09-17
  • 打赏
  • 举报
回复
public class StringTest {
public static void main(String[] args) {
String str = "abcdefghijk";
String newstr = getStr(str);
System.out.println(newstr);
}

static String getStr(String s) {
String newStr = new String();

// get length of string
int temp = s.length();

for (int i = 1; i < temp; i += 2) {
newStr += s.charAt(i);
}

return newStr;
}
}

一个循环就搞定的啊
matrix1984 2012-09-17
  • 打赏
  • 举报
回复
偶数位应该是从索引1开始吧(第二位)。

[Quote=引用 6 楼 的回复:]
Java code


public static void main(String[] args) throws Exception {
String s = "asdfbdfasfdsa";
char[] chars = s.toCharArray();
StringBuffer sb = new StringBuffer()……
[/Quote]
安特矮油 2012-09-17
  • 打赏
  • 举报
回复

public static void main(String[] args) throws Exception {
String s = "asdfbdfasfdsa";
char[] chars = s.toCharArray();
StringBuffer sb = new StringBuffer();
for(int i = 0; i < chars.length; i += 2){
sb.append(chars[i]);
}
System.out.println(sb.toString());
}
Flycutter 2012-09-16
  • 打赏
  • 举报
回复
建议看下StringBuilder类的Javadoc

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧