说明:截取指定字符串个数。
程序清单: SplitString.java
package test;

/**
* 截取字符串的函数,输入为一个字符串和字节数,输出为按字节的字符串,
*但是要保证汉字不被截断半个。
*/
class SplitString
{
String splitStr;
int splitByte;
public SplitString(String str,int bytes)
{
splitStr = str;
splitByte = bytes;
System.out.println("The String is:"+splitStr+";"+"splitBytes="+splitByte);
}
public void SplitIt()
{
int loopCount;
loopCount = (splitStr.length()%splitByte==0?(splitStr.length()/splitByte):
(splitStr.length()/splitByte+1));
System.out.println("Will Split into "+loopCount);
for(int i=1;i<=loopCount;i++)
{
if(i==loopCount)
{
System.out.println(splitStr.substring((i-1)*splitByte,splitStr.length()));
}
else
{
System.out.println(splitStr.substring((i-1)*splitByte,(i*splitByte)));
}
}
}
public static void main(String[] args)
{
SplitString ss = new SplitString("test 中 dd 问 dasf 难道啊 士大夫ssdf 92034urosjd",9);
ss.SplitIt();
}
}
程序清单: SplitString.java
package test;
/**
* 截取字符串的函数,输入为一个字符串和字节数,输出为按字节的字符串,
*但是要保证汉字不被截断半个。
*/
class SplitString
{
String splitStr;
int splitByte;
public SplitString(String str,int bytes)
{
splitStr = str;
splitByte = bytes;
System.out.println("The String is:"+splitStr+";"+"splitBytes="+splitByte);
}
public void SplitIt()
{
int loopCount;
loopCount = (splitStr.length()%splitByte==0?(splitStr.length()/splitByte):
(splitStr.length()/splitByte+1));
System.out.println("Will Split into "+loopCount);
for(int i=1;i<=loopCount;i++)
{
if(i==loopCount)
{
System.out.println(splitStr.substring((i-1)*splitByte,splitStr.length()));
}
else
{
System.out.println(splitStr.substring((i-1)*splitByte,(i*splitByte)));
}
}
}
public static void main(String[] args)
{
SplitString ss = new SplitString("test 中 dd 问 dasf 难道啊 士大夫ssdf 92034urosjd",9);
ss.SplitIt();
}
}
本文介绍了一款Java程序中的实用工具——SplitString类,该类主要用于实现字符串的按字节数进行安全截取,确保汉字不会被截断。通过实例演示了如何使用此工具将长字符串分割成指定长度的子串。

365

被折叠的 条评论
为什么被折叠?



