比较两个字符串并从第二个中删除常见字符并连接不常见?

时间:2017-10-10 11:13:50

标签: java string duplicates

这是比较两个字符串的代码,并从第二个字符串中删除常用字符 并且连接不常见。但输出不合适。

import java.util.*;

class str1 { 
    //create class


    public static void main(String[] args) { 
   //main function

        String str = "hello My name is"; 
    //string one
        String str2 = "viral";  
    //string two


        char s1[] = str.tocharArray();// string convert into character 
        char s2[] = str2.tocharArray();  // string convert into character

        for (int i = 0; i < s1.length; i++) {
            for (int j = 0; j < s2.length; j++) {
                if (s1[i] == s2[j]) {
                    s2[j] = '\0';
                    s2[j] = s2[j + 1];

                }

            }
        }

        String s1cpy = s1.toString();
        String s2cpy = s2.toString();

        String s3 = s1cpy + s2cpy;

        System.out.println("the string after removing common character  and concatenation is " + s3);

    }
}

5 个答案:

答案 0 :(得分:0)

首先,你可以使用替换方法,它更容易。

其次,array.toString()不起作用,你需要使用String.copyValueOf(char [])。

}

也许不是完美的解决方案,但可以像你想要的那样正常工作

答案 1 :(得分:0)

检查你的逻辑,这对我来说似乎不对。看我的代码评论:

for (int i = 0; i < s1.length; i++) {
        for (int j = 0; j < s2.length; j++) {
            if (s1[i] == s2[j]) {
                s2[j] = '\0'; // Here you assign \0 to s2[j]
                s2[j] = s2[j + 1]; // And here you assign s2[j+1] to s2[j], so you overwrite the \0 you just set previously.

            }

        }
    }

答案 2 :(得分:0)

您可以按如下方式更改循环(添加随机字符 - 可能不理想,但会为您提供我认为您想要的输出):

LIKE

答案 3 :(得分:0)

我是这样做的:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("C9")) Is Nothing Then
        ActiveSheet.Name = ActiveSheet.Range("C9")

    End If
End Sub

答案 4 :(得分:0)

检查我的解决方案...

import java.util.*;

public class RCC
{
    public static void main(String [] args)
    {
        String s1 = "", s2 = "";

        Scanner scan = new Scanner(System.in);

        System.out.print("\n Enter the String 1 : ");
        s1 =scan.nextLine();
        System.out.print("\n Enter the String 2 : ");
        s2 =scan.nextLine();

        String a = s1;
        String b = s2;
        char temp = s1.charAt(0);
        String search = "";
        String replace = "";

        for(int i= 0; i < s1.length(); i++)
        {
            temp = s1.charAt(i);
            search = Character.toString(temp);

            for(int j = 0; j < s2.length(); j++)
            {
                if(temp == s2.charAt(j))
                {
                    a = a.replace(search, replace);
                    b = b.replace(search, replace);
                }
            }       
        }

        System.out.println("\n Common Characters Removed String 1 : " + a);
        System.out.println("\n Common Characters Removed String 2 : " + b);

    }
}
相关问题