给定两个字符数组a []和b [],从b []中删除所有出现在数组a []中的所有字符。您需要就地执行此操作,即不使用额外的字符数组。 例如:
Input: a[] = [‘G’, ‘O’]
Input b[] = [‘G’, ’O’, ’O’, ’G’, ’L’, ’E’]
Output: b[] = [‘L’, ‘E’]
代码:
public class ReplaceCharacterArray{
public static void main(String args[]){
char a[] = [‘G’, ‘O’]
char b[] = [‘G’, ’O’, ’O’, ’G’, ’L’, ’E’]
//to replace all the occurences of all the characters of
//a[] array in b[] array we have below logic.
for(int i=0;i<a.length;i++){
for(int j=0;j<b.length;j++){
if(b[j] == a[i]){
//im stuck here how to proceed
}
}
答案 0 :(得分:4)
您无法在Java数组中删除“就地”元素。它们有固定的长度。也就是说,在您的示例中,您将不得不返回一个新数组,因为您无法更改b
数组的长度。
以下是一些指示:
b
数组的写入索引(此索引的左侧,a
中只有字符不存在)。b
数组a
中,前进a
中)与write-index 使用例如Arrays.copyOfRange
将数组的一部分返回到写索引的左侧。
关于您的更新:
[
和]
编写的,字符不是使用‘
编写的,而是将其更改为{
,}
和{{1} }。'
的辅助方法可以更轻松地编写算法boolean arrayContains(char[] arr, char c)
。答案 1 :(得分:0)
你可以这样做
迭代循环a,即2次和 在每次迭代中,执行b []数组中存在的值的copare, 如果是,删除它。继续,直到完全迭代数组b []。
因此,最终你将只有b []数组与其他元素不在数组a []中。
我希望这可以帮助您完成工作。
答案 2 :(得分:0)
您的代码中存在错误,
[
和]
开头和结尾。它们分别以{
和}
开头和结尾。'
。b
中a
中的字符是否存在。remove(char[] array, char characterToRemove)
并传递b[]
并删除相应的字符以完成流程。 更新而不使用String
,StringBuffer
或任何库,这是有效的....
警告数组b
从不减少(它附加NULL
个字符)。我将留给你破解。
/**
* @author The Elite Gentleman
*
*/
public class ReplaceCharacterArray {
public static boolean containsCharacter(char character, char[] array) {
for (int i = 0; i < array.length; i++) {
if (array[i] == character) {
return true;
}
}
return false;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
char a[] = {'G', 'O'};
char b[] = {'G', 'O', 'O', 'G', 'L', 'E'};
//to replace all the occurences of all the characters of a[] array in b[] array we have below logic.
int index = 0;
int count = 0;
while (index < b.length) {
while (ReplaceCharacterArray.containsCharacter(b[index], a)) {
System.arraycopy(b, index + 1, b, 0, b.length - index - 1);
count++;
}
index++;
}
for (int i = (b.length - count); i < b.length; i++) {
b[i]= '\0';
}
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
}
}
答案 3 :(得分:0)
我想因为这是一个家庭作业第三方图书馆可能不被允许。任何方式我只会使用Guava发布代码:
char[] removeChars(char a[],char b[])
{
return CharMatcher.anyOf(new String(b)).removeFrom(new String(a)).toCharArray();
}
更新: (查看此示例,这是一种解决方法)
import java.util.*;
import java.lang.*;
class CharReplace{
public static void main(String[] args)
{
char a[] = "GOOGLE".toCharArray();
char b[] = "GO".toCharArray();
BitSet charToRemove=new BitSet();
for(char c:b)
charToRemove.set(c);
StringBuilder str=new StringBuilder();
for(char c:a)
if(!charToRemove.get(c))
str.append(c);
b=str.toString().toCharArray();
System.out.println(Arrays.toString(b));
}
}