java中关于字符串的操作

现有一串字符串,如javajjjsskjavajavajlll,编写程序将相邻且相同的java替换为单个的java,并计算替换后的字符串中java的个数。
public class Son
{
public static String excute(String str)
{
int size = 0;
int len = str.length();
String newstr="";
boolean bol = false;
int i=0;
while(i< len){
String char1 =String.valueOf(str.charAt(i));
if("j".equals (char1)){
if(i+4 > len){
newstr = newstr+str.substring(i,len);
i=len;
}else {
String s=str.substring(i, i+4);
if("java".equals(s)&& bol==false){
newstr = newstr+str.substring(i,i+4);
i=i+4;
bol=true;
size++;
}else if("java".equals(s)&& bol==true){
i=i+4;
}
else {
newstr=newstr+str.charAt(i);
i++;
bol=false;
}
}

} else {
newstr=newstr+str.charAt(i);
i++;
bol=false;
}
}
System.out.println("size=: "+size);
return newstr;
}
public static void main(String args[])
{
String res = excute("ddddjavajavajajsssjavayyjuaoooojava");
System.out.println(res);
}

/**
2 * 替换字符串函数
3 * @param strSource - 源字符串
4 * @param strFrom - 要替换的子串
5 * @param strTo - 替换为的字符串
6 * @return
7 * @author zzn Date 2009-06-08
8 *
9 */
10 public static String replace(String strSource, String strFrom, String strTo)
11 {
12 // 如果要替换的子串为空,则直接返回源串
13 if(strFrom == null || strFrom.equals(""))
14 return strSource;
15 String strDest = "";
16 // 要替换的子串长度
17 int intFromLen = strFrom.length();
18 int intPos;
19 // 循环替换字符串
20 while((intPos = strSource.indexOf(strFrom)) != -1)
21 {
22 // 获取匹配字符串的左边子串
23 strDest = strDest + strSource.substring(0,intPos);
24 // 加上替换后的子串
25 strDest = strDest + strTo;
26 // 修改源串为匹配子串后的子串
27 strSource = strSource.substring(intPos + intFromLen);
28 }
29 // 加上没有匹配的子串
30 strDest = strDest + strSource;
31 // 返回
32 return strDest;
33 }


Java获取随机字符串


import java.util.Random;
public class getRandomString
{
public static String excute(int length)
{
StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
StringBuffer sb = new StringBuffer();
Random r = new Random();
int range = buffer.length();
for (int i = 0; i < length; i ++)
{
sb.append(buffer.charAt(r.nextInt(range)));
}
return sb.toString();
}
public static void main(String args[])
{
String res = excute(4);
System.out.println(res);
}
}


18 int intPos;
19 // 循环替换字符串
20 while((intPos = strSource.indexOf(strFrom)) != -1)
21 {
22 // 获取匹配字符串的左边子串
23 strDest = strDest + strSource.substring(0,intPos);
24 // 加上替换后的子串
25 strDest = strDest + strTo;
26 // 修改源串为匹配子串后的子串
27 strSource = strSource.substring(intPos + intFromLen);
28 }
29 // 加上没有匹配的子串
30 strDest = strDest + strSource;
31 // 返回
32 return strDest;
33 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值