首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

!字符串"1,2,3,4,5,2,2"怎么变为"1,2,3,4,5,2"(2的个数不一定为2个)

2012-02-08 
求助!字符串1,2,3,4,5,2,2如何变为1,2,3,4,5,2(2的个数不一定为2个)?问题一:假设有一个字符串 1,2,3,

求助!字符串"1,2,3,4,5,2,2"如何变为"1,2,3,4,5,2"(2的个数不一定为2个)?
问题一:
假设有一个字符串 "1,2,3,4,5,2,2 ",我用String[]   mystr=rs.split( ", ");可以将字符串中的 ", "去掉,并保存到数组mystr但是我该把其中的两个2(或多个相同的值)变为1个呢(或者是有个数组有如下值,{1,2,3,4,5,2,2}也是要进行相似的处理)?假设我的字符串中每次只有一个数字出现重复的情况.
请大家来帮帮我呀,急...谢谢了...


[解决办法]
最简单的只能这样了:

public static void main(String args[]) {
String[] str = new String[] { "3 ", "1 ", "2 ", "3 ", "4 ", "5 ", "2 ", "2 "};
Map map = new HashMap();
List tempList = new ArrayList();
for (int i = 0; i < str.length; i++) {
if (!map.keySet().contains(str[i])) {
tempList.add(str[i]);
map.put(str[i], "1 ");
}
}
final int size = tempList.size();
String[] rslt = (String[])tempList.toArray(new String[size]);
for (int j = 0; j < size; j ++) {
System.out.println(rslt[j]);
}
}
[解决办法]
package com.hmilyld;

public class StrSplit {
private void Str(String str) {
String[] temp = str.split( ", ");

for (int i = 0; i < temp.length; i++) {
if (i == 0) {
System.out.print(temp[i]);
} else {
if (!temp[i].equals(temp[i - 1])) {
System.out.print( ", "+temp[i]);
}
}
}
}

public static void main(String[] args) {
StrSplit str = new StrSplit();
str.Str( "1,2,3,4,5,5,5,5,2,2,4,4,6,6,9,9,9,9 ");
}

}

是这个意思不?
[解决办法]
public class 去掉数组中的重复值 {

public static void main(String[] args) {
int[] array = { 1, 2, 1, 3, 3, 4, 5, 5, 6, 7, 2, 2, 9, 8, 9 };

for (int i = 0; i < array.length; i++) {
int temp = array[i];

for (int j = i + 1; j < array.length; j++) {
if (temp == array[j]) {
array[i] = -1;
}
}
}

for (int k = 0; k < array.length; k++) {
if (array[k] != -1) {
System.out.print(array[k]);
}
}
}
}

热点排行