How to use a single replaceall to find the common characters of two strings in Java?

So suppose I have:

String s = "1479K";
String t = "459LP";

I want to come back

String commonChars = "49";

The common character between two strings

Obviously, standard cycles can be used, such as:

String commonChars = "";
for (i = 0; i < s.length; i++)
{
    char ch = s.charAt(i);
    if (t.indexOf(ch) != -1)
    {
        commonChars = commonChars + ch;
    }
}

But I want to be able to do this on one line using replaceall This can be done as follows:

String commonChars = s.replaceAll("["+s.replaceAll("["+t+"]","")+"]","");

My question is: can I use a single call to replaceall to do this? What is a regular expression? I think I must use some kind of foresight, but when I think of it, my brain becomes confused

Solution

String commonChars = s.replaceAll("[^"+t+"]","");
String commonChars = s.replaceAll("[^"+t+"]","");

Note that you may need to escape special characters in T, such as using pattern Quote (T) instead of the above t

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>