字符串操作汇总

来源:互联网 发布:桌面数据恢复软件 编辑:程序博客网 时间:2024/05/16 17:26

 老是有人问我这些字符串操作,现在详细总结:    减去时区   http://blog.csdn.net/zyp009/article/details/12942041

 String str1 = "abcd";    String str2 = "abcdabcd";

//length():求字符串的长度
int len = str1.length();

System.out.println("字符串的长度:" +len);

//2.charAt(int index)取字符串中指定下标的一个元素
for (int i=0;i<len;i++) {
char c = str1.charAt(i);

    System.out.println("下标" + i +"的值:" +c); 

}

//3.codePointAt(int index):index 处字符的代码点值
for (int i=0;i<len;i++) {
int j = str1.codePointAt(i);
System.out.println("下标"+i+"的值:" +j);
}
//4.concat(String str) 将指定字符串连接到此字符串的结尾
String s1 = str1.concat("ABCD");
System.out.println(s1);
String s2 = str1.concat("");
System.out.println(s2);
//5.copyValueOf(char[] data):返回指定数组中表示该字符序列的 String
char[] data = {'a','b','c','d','e','f'};
String str = String.copyValueOf(data);
System.out.println(str);
//6.copyValueOf(char[] data, int offset, int count):返回指定数组中表示该字符序列的 String
char[] data = {'a','b','c','d','e','f'};
String s1 = String.copyValueOf(data, 2, 3);
System.out.println(s1);
//7.endsWith(String suffix):测试此字符串是否以指定的后缀结束
        //startsWith(String prefix)
boolean isd = str1.endsWith("d");
System.out.println("此字符串是否以d结尾:"+isd);
//8.equals(Object anObject):将此字符串与指定的对象比较
boolean iseql = str1.equals("abcd");
System.out.println(iseql);
boolean iseq2 = str1.equals("abc");
System.out.println(iseq2);
//9.equalsIgnoreCase(String anotherString):将此 String 与另一个 String 比较,不考虑大小写
boolean iseql = str1.equalsIgnoreCase("ABCD");
System.out.println(iseql);
//10.getByte():将字符串转化为字节数组
byte[] data = str1.getBytes();
for (int i=0;i<data.length;i++) {
    System.out.println(data[i]+"\t");
}
//indexOf(int ch, int fromIndex):返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索
int i = str2.indexOf(97, 3);
System.out.println(i);
int t = str2.indexOf(99, 1);
System.out.println(t);
int k = str2.indexOf(97,5);

System.out.println(k);

//isEmpty():当且仅当 length() 为 0 时返回 true
boolean isempty1 = str1.isEmpty();
System.out.println(isempty1);
boolean isempty2 = "".isEmpty();

System.out.println(isempty2);

//substring(int beginIndex, int endIndex):返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符
String s1 = str2.substring(4,7);
System.out.println(s1);
String s2 = str2.substring(2,7);
System.out.println(s2);
//toCharArray():将此字符串转换为一个新的字符数组
char[] c = str1.toCharArray();
for (int r=0;r<c.length;r++){
  System.out.print(c[r]+"\t");
}
//valueOf
1. 由 基本数据型态转换成 String 
String 类别中已经提供了将基本数据型态转换成 String 的 static 方法 
也就是 String.valueOf() 这个参数多载的方法 
有下列几种 
String.valueOf(boolean b) : 将 boolean 变量 b 转换成字符串 
String.valueOf(char c) : 将 char 变量 c 转换成字符串 
String.valueOf(char[] data) : 将 char 数组 data 转换成字符串 
String.valueOf(char[] data, int offset, int count) : 
将 char 数组 data 中 由 data[offset] 开始取 count 个元素 转换成字符串 
String.valueOf(double d) : 将 double 变量 d 转换成字符串 
String.valueOf(float f) : 将 float 变量 f 转换成字符串 
String.valueOf(int i) : 将 int 变量 i 转换成字符串 
String.valueOf(long l) : 将 long 变量 l 转换成字符串 
String.valueOf(Object obj) : 将 obj 对象转换成 字符串, 等于 obj.toString() 
用法如: 
int i = 10; 
String str = String.valueOf(i); 
这时候 str 就会是 "10" 
2. 由 String 转换成 数字的基本数据型态 
要将 String 转换成基本数据型态转 
大多需要使用基本数据型态的包装类别 
比如说 String 转换成 byte 
可以使用 Byte.parseByte(String s) 
这一类的方法如果无法将 s 分析 则会丢出 NumberFormatException 
byte : 
Byte.parseByte(String s) : 将 s 转换成 byte 
Byte.parseByte(String s, int radix) : 以 radix 为基底 将 s 转换为 byte 
比如说 Byte.parseByte("11", 16) 会得到 17 
double :  Double.parseDouble(String s) : 将 s 转换成 double 
float :  Double.parseFloat(String s) : 将 s 转换成 float 
int :  Integer.parseInt(String s) : 将 s 转换成 int 
long :  Long.parseLong(String s)

3. final String url = "http://www.263.net/images/kk/sim_1.jpg";

String parts[] = url.split("/", 5);// ==》images/sim_1.jpg    截取字符串,指明大小
int location = (int) (Math.random()*ips.length);
location = 0;
String ip = ips[location];
//别越界了
String filePath = "http://"+ip+"/"+parts[4];
filePath = filePath.replace(".jpg", ".mp4"); //替换
System.out.println(filePath); //==>http://123.129.249.204/kk/sim_1.mp4

4. String url = http://v.cctv.com/flash/mp4video4/qgds/2010/08/07/qgds_h264418000nero_aac32_20100807_1281191449601-1.mp4&2&3&4&5&6&7&8&9

截取mp4以前的  url = url.substring(0,  mUrl.lastIndexOf(".mp4") + 4);

打出的log:url= http://v.cctv.com/flash/mp4video4/qgds/2010/08/07/qgds_h264418000nero_aac32_20100807_1281191449601-1.mp4

5. 截取 String mUrl = "http://www.263.net/images/sim_1.jpg";

mUrl = mUrl.substring(mUrl.lastIndexOf("/") + 1, mUrl.length());

打出log:sim_1.jpg

6.String转换为int型;
String str;     int i = Integer.parseInt(str);
int型转换为String;   int i;    String str = i.toString();
//convert i(int) to j(Integer)
int i;    Integer j = Integer.valueOf(i);
//convert t(Integer) to n (int)
Integer t;   int n = t.intValue();

<表达式1>?<表达式2>:<表达式3>; "?"运算符的含义是: 先求表达式1的值, 如果为真, 则执行表达式2,并返回表达式2的结果 ; 如果表达式1的值为假, 则执行表达式3 ,并返回表达式3的结果. ===》mFirstMenuList.size() > 0 ? mFirstMenuList.get(0).mId : "-1"

UNIX时间戳转换工具 : http://shijianchuo.911cha.com/

(一)获取总根
File[] fileList=File.listRoots();  
//返回fileList.length为1  
//fileList.getAbsolutePath()为"/"  
//这就是系统的总根  
(二)打开总根目录
File file=new File("/");  
File[] fileList=file.listFiles();  
//获取的目录中除了"/sdcard"和"/system"还有"/data"、"/cache"、"/dev"等  
//Android的根目录并不像Symbian系统那样分为C盘、D盘、E盘等  
//Android是基于Linux的,只有目录,无所谓盘符  
(三)获取系统存储根目录
File file=Environment.getRootDirectory();//File file=new File("/system");  
File[] fileList=file.listFiles();  
//这里说的系统仅仅指"/system"  
//不包括外部存储的手机存储的范围远远大于所谓的系统存储  
(四)获取SD卡存储根目录
File file=Environment.getExternalStorageDirectory();//File file=new File("/sdcard");  
File[] fileList=file.listFiles();  
//要获取SD卡首先要确认SD卡是否装载  
boolean is=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);  
//如果true,则已装载  
//如果false,则未装载  
(五)获取data根目录
File file=Environment.getDataDirectory();//File file=new File("/data");  
File[] fileList=file.listFiles();  
//由于data文件夹是android里一个非常重要的文件夹,所以一般权限是无法获取到文件的,即fileList.length返回为0  
(六)获取私有文件路径
Context context=this;//首先,在Activity里获取context  
File file=context.getFilesDir();  
String path=file.getAbsolutePath();  
//此处返回的路劲为/data/data/包/files,其中的包就是我们建立的主Activity所在的包  
//我们可以看到这个路径也是在data文件夹下  
//程序本身是可以对自己的私有文件进行操作  
//程序中很多私有的数据会写入到私有文件路径下,这也是android为什么对data数据做保护的原因之一  
(七)获取文件(夹)绝对路径、相对路劲、文件(夹)名、父目录
File file=……  
String relativePath=file.getPath();//相对路径  
String absolutePath=file.getAbsolutePath();//绝对路径  
String fileName=file.getName();//文件(夹)名  
String parentPath=file.getParent();//父目录  
(八)列出文件夹下的所有文件和文件夹
File file=……  
File[] fileList=file.listFiles();  
(九)判断是文件还是文件夹
File file=……  
boolean is=file.isDirectory();//true-是,false-否  
(十)判断文件(夹)是否存在
File file=……  
boolean is=file.exists();//true-是,false-否  
(十一)新建文件(夹)
File file=……  
oolean is=file.isDirectory();//判断是否为文件夹  
/*方法1*/  
if(is){  
    String path=file.getAbsolutePath();  
    String name="ABC";//你要新建的文件夹名或者文件名  
    String pathx=path+name;  
    File filex=new File(pathx);  
    boolean is=filex.exists();//判断文件(夹)是否存在  
    if(!is){  
        filex.mkdir();//创建文件夹  
        //filex.createNewFile();//创建文件  
    }  
/*方法2*/  
if(is){
    String path=file.getAbsolutePath();  
    String name="test.txt";//你要新建的文件夹名或者文件名  
    File filex=new File(path,name);//方法1和方法2的区别在于此  
    boolean is=filex.exists();//判断文件(夹)是否存在  
    if(!is){  
        filex.mkdir();//创建文件夹  
        //filex.createNewFile();//创建文件  
}  
(十二)重命名文件(夹)
File file=……  
String parentPath=file.getParent();  
String newName="name";//重命名后的文件或者文件夹名  
File filex=new File(parentPath,newName);//File filex=new File(parentPaht+newName)  
file.renameTo(filex);  
(十三)删除文件(夹)
File file=……  
file.delete();//立即删除  
//file.deleteOnExit();//程序退出后删除,只有正常退出才会删除
13. //  获取该程序的安装包路径
String path=getApplicationContext().getPackageResourcePath();
//  获取程序默认数据库路径
getApplicationContext().getDatabasePath(s).getAbsolutePath();
http://blog.sina.com.cn/s/blog_7ed4baf90101nxh8.html
14.字符串分拆
String value = "电影,教育,电视剧,纪录片,综艺";
String[]  sourceStrArray = value.split(",");
System.out.println(sourceStrArray.length);
 //字符串如何拆分到集合
 String str = "a,b,c,d";
 String[] strs = str.split(",");
 List<String> list = Arrays.asList(strs);
 for(String s : list) {
        System.out.println(s);
 }
15.数据结构相关
PlayerInfo info = new EpgDetailData.PlayerInfo();

ArrayList<CollectBean> data = (ArrayList<CollectBean>) msg.obj;
SearchBean data = (SearchBean) msg.obj;

private ArrayList<InfoBean> list_Record_bean = new ArrayList<InfoBean>();
private ArrayList<ArrayList<CatgiteminfoBean>> list_Record_list = new ArrayList<ArrayList<CatgiteminfoBean>>();

String[][]是二维数组。例如:String[][] str=new String[4][4],这是创建了一个有4行4列元素的数组。
String[]代表一维数组。例如:String[] str=new String[4],这个创建一个有4个元素的数组。

private Integer[]   mImageIds   =  { 
            R.drawable.img1, 
            R.drawable.img2, 
            R.drawable.img3, 
            R.drawable.img1, 
    };

private static final String[] firstStr = new String [] {
  "点播", "电视", "音乐"
};
Object object = parent.getItemAtPosition(position);
if (object instanceof SearchMenuBean) { //instanceof关键字用于判断一个引用类型变量所指向的对象是否是一个类(或接口、抽象类、父类)的实例
ArrayList<SearchMenuBean> list = SearchMenuBean.getList();

if (list != null && list.size() > 0) {
if (list_adapter02 != null) {
list_adapter02.clearData();
list_adapter02.setList(list);
list_adapter02.notifyDataSetChanged();
}
}
}
16.代码中换行,需要用一个默认的字符串,然后替换

tv.setText((this.getString(R.string.hello_world) + "|" + this.getString(R.string.app_test)).replace("|", "\n"));

17.删除v开头的
root@ysten-e4-gw:/data/data/com.istv.launcher/files # rm V*
rm V*

18.删除一个目录下文件

root@ysten-e4-gw:/data/data/com.istv.launcher/files # busybox rm -fr *  //删除一个目录下文件
busybox rm -fr *

19.读取ini文件

String configpath = "/system/etc/ini/Vers.ini";  
    FileInputStream fis = null; // 读  
    Properties mProperties = null; 

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mProperties = new Properties();

new Thread() { 
@Override
public void run() {
super.run();
try {
fis = new FileInputStream(configpath);
mProperties.load(fis);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}  catch(IOException e) {


String RomVersionInfo = mProperties.get("VersionInfo").toString();// 获取rom软件信息号
String RomVersionId = mProperties.get("VersionId").toString();//获取rom当前版本号
}
}.start();
}

写ini文件也可用此方法,但准确度不高,原来的ini文件顺序发生改变,还添加了头标示,但是这些不影响具体的读取、写入,对于较严格的格式要求,不提倡这种方法
fos=new FileOutputStream(configpath);//加载读取文件流  
pp.setProperty("Sound", "trunoff");// 修改值  
pp.store(fos, null);//修改值  
fos.close();  

21.gfg

for (int i = 0; i<10; i++) {...//插入语句 }

用while来写
int i = 0;
while (i<10) {
  ...//插入语句
  i++;
}
for循环比较简洁,会比while更常用些,尤其是用array的时候,很方便的。

但是如果想做无限循环,while更方便点,比如说
int i = 1;
while (i == 1){ ... }

22.ff