一、将字符串中的相同元素简化,即只将第一个输出,其它的不输出。
例:“ilovejava”-->"iloveja"
我的代码为
/*
* Created on 2004-4-7
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
/**
* @author ai92
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
import java.io.*;
public class Jiaogu
{
private String gets=null;//定义字符串接受将要处理的字符串
public static void main(String[] args)throws Exception
{
Jiaogu jg=new Jiaogu();
jg.getString();
jg.qurongyu();
}
private void qurongyu()//冗余处理函数
{
System.out.println("去冗余输出为:");
System.out.print(gets.charAt(0));
for(int i=1;i<gets.length();i++)
{
boolean key=true;
for(int j=i-1;j>=0;j--)
{
if(gets.charAt(i)==gets.charAt(j))
{
key=false;
break;
}
}
if(!key)
continue;
if(key)
{
System.out.print(gets.charAt(i));
}
}
}
private void getString()throws IOException //从键盘接受字符串
{
System.out.println("请输入要去冗余的字符串:");
BufferedReader bfs=new BufferedReader(new InputStreamReader(System.in));
gets=bfs.readLine();
bfs.close();
}
}
大致相同,改改应该就行
例:“ilovejava”-->"iloveja"
我的代码为
/*
* Created on 2004-4-7
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
/**
* @author ai92
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
import java.io.*;
public class Jiaogu
{
private String gets=null;//定义字符串接受将要处理的字符串
public static void main(String[] args)throws Exception
{
Jiaogu jg=new Jiaogu();
jg.getString();
jg.qurongyu();
}
private void qurongyu()//冗余处理函数
{
System.out.println("去冗余输出为:");
System.out.print(gets.charAt(0));
for(int i=1;i<gets.length();i++)
{
boolean key=true;
for(int j=i-1;j>=0;j--)
{
if(gets.charAt(i)==gets.charAt(j))
{
key=false;
break;
}
}
if(!key)
continue;
if(key)
{
System.out.print(gets.charAt(i));
}
}
}
private void getString()throws IOException //从键盘接受字符串
{
System.out.println("请输入要去冗余的字符串:");
BufferedReader bfs=new BufferedReader(new InputStreamReader(System.in));
gets=bfs.readLine();
bfs.close();
}
}
大致相同,改改应该就行
如要检查的单个字符为a,则可以大概像下面这样判断
int temp=a&0x000000ff;
if(!boolean[temp]) //如果这是个新字符
......do what you want
boolean[temp]=true;else //这是个已出现字符
.....do what you want
String -> HashSet -> String
import java.util.*;public class GuoLv{
public String getNewString(String str){
char[] chars=str.toCharArray();//转变成字符数组
String[] strs=new String[chars.length];
for(int i=0;i<strs.length;i++){//转变成字符串数组
strs[i]="";
strs[i]+=chars[i];
} TreeSet contain=new TreeSet(); for(int i=0;i<strs.length;i++)//把数组装入容器
contain.add(strs[i]); Iterator it=contain.iterator();
String string="";
while(it.hasNext())
string+=it.next();//从容器中取出
return string;
} public static void main(String[] args){
GuoLv guoLv=new GuoLv();
String str="abababds";
str=guoLv.getNewString(str);
System.out.println(str);
}
}