2013-04-26 64 views
-1

我有这样一个字符串String no1="c1245_f5";,我有另一个像这样的字符串String no2="456df";,我想用第二个字符串替换第一个字符串,但只在第一个字符后面。如何在单个字符后替换字符串?

在这个我有替换后c。我的输出必须像c456df。我不知道这样做。我试图更换整个字符串

String no2="456df"; 
String no1="c1245_f5"; 
int g; 
g=no1.indexOf("c"); 
int h=no1.indexOf("_", g+1); 
no1=no1.substring(g, h); 

System.out.println("Number-"+no1); 

String rep=no1.replaceAll(no1,no2); 

System.out.println(rep); 

这里的输出只是第二个字符串。

编辑:

预期输出:

c456df 

输出我得到:

456df 
+0

什么是你期望的输出,你得到什么? – 2013-04-26 12:20:39

+0

那么你期望输出什么? – 2013-04-26 12:20:42

+0

写出你想要的输出 – 2013-04-26 12:21:09

回答

4

然后通过连接s1.substring(0, 1)s2创建一个字符串S3

String s1 ="c1245_f5"; 
String s2 = "456df"; 
String s3 = s1.substring(0, 1) + s2; 

它会给输出c456df

SEE HERE

+0

@Vignesh Vino你解决了问题吗 – PSR 2013-04-26 12:24:32

+0

是的,我解决了..不能接受任何答案。它要求我等9分钟 – 2013-04-26 12:26:23

5

不需要String.replaceAll,试试这个

String s1 ="c1245_f5"; 
    String s2 = "456df"; 
    String s3 = s1.substring(0, 1) + s2; 
0

你可以做到这一点,如下所示:

String no1 = "c1245_f5"; 
String no2 = "456df"; 
String no3 = no1.charAt(0) + no2; 
2

非常首先,我想到的是使用String.substring(int,int)

因此,代码会是这样的:

String tmp=c1.substring(0,1)+no2; 
System.out.println(tmp); 

退房的documentation,以获取有关的String功能的更多信息。

0

我会建议你使用这样的:

String rep = no1.replace(no1.substring(1), no2); 

是您所做的错误是,你应该考虑的“C”字后的第一个位置。所以的indexOf( 'C')+ 1

把你的代码应该是:

String no2="456df"; 
    String no1="c1245_f5"; 
    String rep = no1.replace(no1.substring(no1.indexOf("c")+1), no2); 
    System.out.println(rep); 
0

走索引,然后追加第二个字符串。

String s1 ="c1245_f5"; 
String index = s1.substring(0, 1) 
String s2 = index + "456df"; 
0

尝试

String no1 ="c1245_f5"; 
String no2= "456df"; 
int len=no1.length(); 
String no3= no1.substring(1,len); 
String newNo1=no1.replace(s3, s2);