在java中按字符比较两个字符串

时间:2014-08-16 18:08:57

标签: java string

我有2个字符串:

  • first =“BSNLP”

  • second =“PBN”(或用户输入的任何内容)。

要求是,O / P应该返回仅包含第一个但不包含第二个字符的字符串。 例如。在这种情况下,O / P是SL

为Eg2。

  • first =“ASDR”
  • second =“MRT”

,o / p =“ASD”

为此,我开发了编码:

String one = "pnlm";
String two ="bsnl";
String fin = "";

for(int i =0; i<one.length();i++)
        {
            for(int j=0;j<two.length();j++)
            {

                //System.out.print(" "+two.charAt(j));

                if(one.charAt(i) == two.charAt(j))
                {
                    fin+=one.charAt(i);

                }

            }

        }

ch=removeDuplicates(fin);
        System.out.print(" Ret ::"+fin);

        System.out.println("\n Val ::"+ch);

CH给了我相同字符的字符串,但是使用这个逻辑我不能得到不相等的字符。

有人可以帮忙吗?

4 个答案:

答案 0 :(得分:3)

您可以使用Set interface添加所有第二个字符数组,以便日后查看。

<强>样品:

String one = "ASDR";
String two ="MRT";
StringBuilder s = new StringBuilder();

Set<Character> set = new HashSet<>();
for(char c : two.toCharArray())
    set.add(c); //add all second string character to set
for(char c : one.toCharArray())
{
    if(!set.contains(c)) //check if the character is not one of the character of second string
        s.append(c); //append the current character to the pool
}

System.out.println(s);

<强>结果:

ASD

答案 1 :(得分:1)

我简单地交换你的逻辑: - 字符串一=&#34; pnlm&#34 ;;
字符串二=&#34; bsnl&#34 ;;
String fin =&#34;&#34 ;;
int cnt;
for(int i = 0; i&lt; one.length(); i ++)
{
                cnt = 0; //零,没有字符相等             for(int j = 0; j&lt; two.length(); j ++)
            {
              // System.out.print(&#34;&#34; + two.charAt(j));

            if(one.charAt(i) == two.charAt(j))
            {
               cnt = 1;     // ont for character equal
            }

        }
if(cnt == 0)
fin+=one.charAt(i);
    }

    System.out.print(" Ret ::"+fin);

o / p: Ret :: pm

答案 2 :(得分:0)

public static void main(String[] args) 
{
    String one = "ASDR";
    String two ="MRT";
    String fin = unique(one, two);

    System.out.println(fin);
}

private static String unique(final String one,
                             final String two)
{
    final List<Character> base;
    final Set<Character>  toRemove;
    final StringBuilder   remaining;

    base = new ArrayList<>(one.length());
    toRemove = new HashSet<>();

    for(final char c : one.toCharArray())
    {
        base.add(c);
    }

    for(final char c : two.toCharArray())
    {
        toRemove.add(c);
    }

    base.removeAll(toRemove);
    remaining = new StringBuilder(base.size());

    for(final char c : base)
    {
        remaining.append(c);
    }

    return (remaining.toString());
}

答案 3 :(得分:-1)

  1. 迭代第一个字符串
  2. 对于每个字符,检查第二个字符串是否包含它
  3. 如果没有,请将该字符添加到StringBuilder
  4. 返回stringBuilder.toString()
相关问题