第1个回答 2013-08-11
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JOptionPane;
public class CharSet {
public static void main(String[] args) {
String set1 = getInputString("请输入第一个集合的元素");
String set2 = getInputString("请输入第二个集合的元素");
CharSet charSet = new CharSet(set1, set2);
StringBuffer message = new StringBuffer("set1 == " + set1 + ", set2 == " + set2).append("\n");
message.append("Set1∪Set2 == ").append(charSet.or()).append("\n");
message.append("Set1∩Set2 == ").append(charSet.and()).append("\n");
message.append("Set1-Set2 == ").append(charSet.subtract()).append("\n");
JOptionPane.showMessageDialog(null, message);
}
private static String getInputString(String msg) {
String input = null;
while(true){
input = JOptionPane.showInputDialog(msg);
if(input == null || input.trim().length() == 0)
JOptionPane.showMessageDialog(null, "忽悠我是吧, 别正个空的集合啊 ~");
else
return input;
}
}
private String set1;
private String set2;
public CharSet(String set1, String set2) {
this.set1 = filter(set1);
this.set2 = filter(set2);
}
private String filter(String string) {
return string.replaceAll("[^a-z]", "");
}
/** 并 */
public String or(){
Set<Character> buf = new TreeSet<Character>();
addAll(buf, set1);
addAll(buf, set2);
return toString(buf);
}
/** 交 */
public String and(){
Set<Character> buf = new TreeSet<Character>();
for(char c:set1.toCharArray()){
if(set2.contains(String.valueOf(c))){
buf.add(Character.valueOf(c));
}
}
return toString(buf);
}
/** 差 */
public String subtract(){
Set<Character> buf = new TreeSet<Character>();
addAll(buf, set1);
for(char c:set2.toCharArray()){
if(buf.contains(Character.valueOf(c))){
buf.remove(Character.valueOf(c));
}
}
return toString(buf);
}
private String toString(Set<Character> buf){
StringBuffer s = new StringBuffer();
for(Character c:buf){
s.append(c);
}
return s.toString();
}
private void addAll(Set<Character> buf, String set) {
for(char c:set.toCharArray()){
buf.add(Character.valueOf(c));
}
}
}
第2个回答 2013-08-11
C语言的行不?
#include <stdio.h>
#include <stdlib.h>
int a[30],b[30],ans[30];
int n,m;
void jiao()
{
int i;
for(i=0;i<26;i++)
if(a[i] && b[i])
ans[i]=1;
else ans[i]=0;
}
void bing()
{
int i;
for(i=0;i<26;i++)
if(a[i] || b[i])
ans[i]=1;
else ans[i]=0;
}
void cha()
{
int i;
for(i=0;i<26;i++)
if(a[i] && !b[i])
ans[i]=1;
else ans[i]=0;
}
void display()
{
int i,t;
t=1;
for(i=0;i<26;i++)
if(ans[i])
{
printf("%c ",i+'a');
t=0;
}
if(t)printf("结果为空集合");
printf("\n");
}
int main()
{
int i;
char ch[10];
printf("请输入第一个集合的元素个数:");
scanf("%d",&n);
printf("请输入第一个集合的元素:");
for(i=0;i<26;i++)
{
a[i]=0;
b[i]=0;
ans[i]=0;
}
for(i=0;i<n;i++)
{
scanf("%s",ch);
a[ch[0]-'a']=1;
}
printf("请输入第二个集合的元素个数:");
scanf("%d",&m);
printf("请输入第二个集合的元素:");
for(i=0;i<m;i++)
{
scanf("%s",ch);
b[ch[0]-'a']=1;
}
printf("请输入要做的操作:\n");
printf("1.交\n");
printf("2.并\n");
printf("3.差\n");
scanf("%d",&i);
if(i<1 || i>3)
return 0;
switch(i)
{
case 1:
jiao();
break;
case 2:
bing();
break;
case 3:
cha();
break;
}
display();
system("pause");
return 0;
}