The algorithm idea of this problem is to compare each character in string 1 with each character in String 2, encounter a common-owned character, put it in another array, and then output it in the final order.
But the difficulty with this problem is how to rule out duplicate characters.
Public classBothchar { Public Staticstring Bothchar (String str1,string str2) {stringbuffer sb=NewStringBuffer (); intN1,n2,m=0; //Char a[]=new char[50];n1=str1.length (); N2=str2.length (); if(str1!=NULL){//gets each character in the string 1 for(inti=0;i<n1;i++){ Charc =Str1.charat (i); } } //gets each character in the string 2 if(str2!=NULL){//gets each character in the string 1 for(intj=0;j<n2;j++){ CharD =Str2.charat (j); } } //two characters in a string are compared for(inti=0;i<n1;i++) {m=0; for(intj=0;j<n2;j++){ if(Str1.charat (i) ==str2.charat (j) &&m==0) {sb.append (Str1.charat (i)); M=1; } } } returnsb.tostring (); } }
WORKAROUND: Set the flag bit m before the inner loop, if m=0, indicating that the character does not appear in the string 2, and then the inner loop, the inner loop of the m=1, so that you can exclude a string in the occurrence of repeated characters, the specific code attached, for everyone to refer to
Using Java programming to find two characters in a string