我需要从字符数组中删除一个字符并重新调整数组的大小。到目前为止,我一直致力于用特殊角色替换特定角色。
在这段代码中,我正在搜索所有找到的匹配项,即如果在男性和女性角色数组中匹配任何字符,如果找到,我将用“*”替换它。而不是我必须删除该字符并调整数组大小。
private static void Compare(String Male,String Female) {
char[] male;
char[] female;
// converting a string into charecter array
male=Male.toCharArray();
female=Female.toCharArray();
//finding any matches i.e, any charecter is matching or not
for(int i=0;i<male.length;i++){
for(int j=0;j<female.length;j++)
{
String m = Character.toString(male[i]);
String fm = Character.toString(female[j]);
if(m.equals(fm)){
//if the charecters are equal then replacing them with "*"
male[i]='*';
female[j]='*';
}
}
}
答案 0 :(得分:3)
试试这个:
String male = "maleg*$m-z";
String female= "femal^\\$e-is";
String deletedMale = male.replaceAll("["+Pattern.quote(female)+"]", "");
String deletedFemale = female.replaceAll("["+Pattern.quote(male)+"]", "");
System.out.println(deletedMale);
System.out.println(deletedFemale);
答案 1 :(得分:0)
您可以在org.apache.commons.lang中使用ArrayUtils类 库使这更容易: Array Utils Link
public static void main(String[] args) {
String Male = "male";
String Female = "female";
char[] male;
char[] female;
// converting a string into charecter array
male=Male.toCharArray();
female=Female.toCharArray();
//finding any matches i.e, any charecter is matching or not
for(int i=0;i<male.length;){
boolean remove = false;
for(int j=0;j<female.length;)
{
String m = Character.toString(male[i]);
String fm = Character.toString(female[j]);
if(m.equals(fm)){
//if the charecters are equal then replacing them with "*"
female = ArrayUtils.remove(female, j);
remove = true;
}else{
j++;
}
}
if(remove)
{
male = ArrayUtils.remove(male, i);
}else{
i++;
}
}
System.out.println(male);
System.out.println(female);
}
答案 2 :(得分:0)
嗯,您的代码存在很多问题。也就是说,缺乏惯例,没有回报价值,而且几乎没有明确问题究竟是什么。
无论如何,只有当字符出现在两个字符串中时,才会删除重复项。
private static void compare(String male, String female) {
List<Character> male1 = addAll(male.toCharArray());
List<Character> female1 = addAll(female.toCharArray());
for (int i = 0; i < male1.size(); i++) {
Character c = male1.get(i);
if (female1.contains(c)) {
while (male1.remove(c)) {
i--;
}
while (female1.remove(c));
}
}
// Do whatever else here, unless you need a char array, then convert it
// if you need to.
char[] maleA = toArray(male1);
char[] femaleA = toArray(female1);
System.out.println(new String(maleA));
System.out.println(new String(femaleA));
}
以下是上述代码中引用的方法。
private static char[] toArray(List<Character> list) {
char[] array = new char[list.size()];
for (int i = 0; i < array.length; i++) {
array[i] = list.get(i);
}
return array;
}
private static List<Character> addAll(char[] array) {
List<Character> list = new ArrayList<Character>();
for (char c : array) {
list.add(c);
}
return list;
}
如果您需要使用其他数据类型,只需制作通用版本或更改它。
答案 3 :(得分:0)
您可以使用以下功能轻松实现此目的:
String original_str="HOLLOW POOL";
String newone=original_str.replace("O", "*"); //Replaces the char "O" with "*"
System.out.print(newone);
结果将是H * LL * W P ** L
就是这样!!