java 去掉字符串中相同的字符串,比较Java中的字符串,并删除字符串相同的部分...

I have two strings with me:

s1="MICROSOFT"

s2="APPLESOFT"

I need to compare the strings and remove the duplicate part (always towards the end) from the second string. So I should get "MICROSOFT" and "APPLE" as output.

I have compared both the strings character by character.

String s1 = "MICROSOFT";

String s2 = "APPLESOFT";

for(int j=0; j

{

char c1 = s1.charAt(j);

char c2 = s2.charAt(j);

if(c1==c2)

System.out.println("Match found!!!");

else

System.out.println("No match found!");

}

It should check the strings and if the two strings have same characters until the end of string, then I need to remove that redundant part, SOFT in this case, from the second string. But I can't think of how to proceed from here.

There can be more duplicates...but we have to remove only those which are continuously identical. if i have APPWWSOFT and APPLESOFT, i should get APPLE again in the second string since we got LE different than WW in between

Can you guys please help me out here?

解决方案

I have solved my problem after racking some brains off. Please feel free to correct/improve/refine my code. The code not only works for "MICROSOFT" and "APPLESOFT" inputs, but also for inputs like "APPWWSOFT" and "APPLESOFT" (i needed to remove the continuous duplicates from the end - SOFT in both the above inputs). I'm in the learning stage and I'll appreciate any valuable inputs.

public class test

{

public static void main(String[] args)

{

String s1 = "MICROSOFT";

String s2 = "APPLESOFT";

int counter1=0;

int counter2=0;

String[] test = new String[100];

test[0]="";

for(int j=0; j

{

char c1 = s1.charAt(j);

char c2 = s2.charAt(j);

if(c1==c2)

{

if(counter1==counter2)

{

//System.out.println("Match found!!!");

test[0]=test[0]+c2;

counter2++;

//System.out.println("Counter 2: "+counter2);

}

else

test[0]="";

}

else

{

//System.out.print("No match found!");

//System.out.println("Counter 2: "+counter2);

counter2=counter1+1;

test[0]="";

}

counter1++;

//System.out.println("Counter 1: "+counter1);

}

System.out.println(test[0]);

System.out.println(s2.replaceAll(test[0]," "));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值