这段对二进制数据切割的代码是对一整串二进制数据按规则切割。连续1遇0切割,连续0遇1切割,带X的用规则切割。可以加个计算出切割后以1开头的字符串和以0开头的字符串的数量的代码吗。
import java.io.;
public class aa {
/*
* 在源数据中将指定字符替换成最后的数字
* @param sourceData
* @param repalceChar
* @param index
* @return
*/
public static String replaceDataFromTail(String sourceData, String repalceChar,int index) {
if (!sourceData.substring(index, index + 1).equals(repalceChar)) {
return sourceData.replaceFirst(repalceChar, sourceData.substring(index, index+1));
}
if (sourceData.substring(index, index + 1).equals(repalceChar)&& (index== sourceData.length()-1)) {
return sourceData.replaceFirst(repalceChar, sourceData.substring(index, index+1));
}
return replaceDataFromTail(sourceData, repalceChar,index+1);
}
/**
* 在源数据中用前面的数字替换指定字符
* @param sourceData
* @param repalceChar
* @param index
* @return
*/
public static String replaceDataFromHead(String sourceData, String repalceChar,int index) {
if (index> sourceData.length()-1) {
return sourceData;
}
if (!sourceData.substring(index,index+1).equals(repalceChar)) {
return sourceData;
}
String prevOneChar= "";
String prevTwoChar= "";
String prevThreeChar= "";
switch (index)
{
case 0:
break;
case 1:
prevOneChar = sourceData.substring(index - 1, index);
sourceData = sourceData.replaceFirst(repalceChar, prevOneChar);
sourceData = replaceDataFromHead(sourceData, repalceChar, index + 1);
break;
case 2:
prevOneChar = sourceData.substring(index - 1, index);
prevTwoChar= sourceData.substring(index-2, index-1);
if(prevOneChar.equals(prevTwoChar)) {
sourceData = sourceData.replaceFirst(repalceChar, prevOneChar);
sourceData = replaceDataFromHead(sourceData, repalceChar, index + 1);
}
else
{
return replaceDataFromTail(sourceData,repalceChar,index);
}
break;
default:{
prevOneChar = sourceData.substring(index - 1, index);
prevTwoChar= sourceData.substring(index-2, index-1);
prevThreeChar= sourceData.substring(index-3, index-2);
if ((!prevThreeChar.equals(prevTwoChar)|| prevTwoChar.equals(prevOneChar))&&(!prevOneChar.equals(repalceChar)))
{
sourceData= sourceData.replaceFirst(repalceChar, prevOneChar);
sourceData= replaceDataFromHead(sourceData,repalceChar,index+1);
}
else
{
return replaceDataFromTail(sourceData,repalceChar,index);
}
}
}
return sourceData;
}
/**
* 根据规则拆分指定字符串
* @param sourceData
* @return
*/
public static String splitData(String sourceData, String repalceChar)
{
String tmpData= "";
int startIndex= -1;
for (int index=0;index< sourceData.length();index++){
if (sourceData.substring(index,index+1).equals(repalceChar)) {
sourceData= replaceDataFromHead(sourceData,repalceChar,index);
}
if (startIndex==-1) {
startIndex = index;
continue;
}
if (!sourceData.substring(index,index+1).equals(sourceData.substring(index-1,index)))
{
tmpData= tmpData+" "+ sourceData.substring(startIndex,index+1);
startIndex= -1;
}
}
if (startIndex!= -1)
{
tmpData= tmpData+" "+ sourceData.substring(startIndex,sourceData.length());
}
return tmpData;
}