JAVA学习笔记0006----String的简单用法

在java的编程过程中,查看API文档的能力是基本技能之一。其中有一个类是我们经常用到的,它就是String类,在这里我们简单介绍一下它的类型和用法:
在一个类中构造函数是比较重要的,通过查看API文档我们可以看出String类有一系列的构造函数供大家使用,这里我就不一一赘述了。下面讲一些常见的String方法。

常用类:
字符串类(String StringBuffer)
基本数据类型包装类
Math类
File类
枚举类
String(不可变的字符序列)常见的构造方法:
public char charAt(int index)
返回字符串中的第index个字符
public int length()
返回字符串的长度
public int indexOf(String str, int fromIndex)
返回字符串中出现的str的第一个位置
public boolean equalsIgnoreCase(String anotner)
比较字符串与anothershi是否一样(忽略大小写)
public String replace(char oldChar, char newChar)
在字符串中用newChar字符替换oldChar字符
public boolean startsWith(String prefix)
判断字符串是否已prefix字符串开头
public boolean endsWith(String prefix)
判断字符串是否已prefix字符串结尾
public String toUpperCase()
返回一个字符串为该字符串的大写形式
public String toLowerCase()
public String substring(int beginIndex)
返回该字符串从beginIndex开始到结尾的字符串
public String subString(int beginIndex, int endIndex)
返回该字符串从beginIndex开始到endIndex结尾的字符串
public String trim()
返回将该字符串去掉开头和结尾空格后的字符串

静态重载方法:
public static String valueOf()将基本类型转换成字符串类型
入参为int n, double b...
方法public Stringp[] spit(String regex)可以将一个字符串按照指定的分隔符分隔,返回分隔后的字符串数组
indexOf()
返回指定字符第一次发生的字符串内的索引(此方法中一系列的重载方法供大家选用)。
下面写几个小的例子来展示String的方法的用法:
1、找出字符串中的大写字母、小写字母和其他符号的个数:
public class Demo {
public static void main(String args[]) {
String s = "ASDFGsdf333####$5OOOOOOODDDDDsceMJEnjkNKNKnj";
int lCount = 0, uCount = 0, oCount = 0;
for(int i = 0; i < s.length(); i ++) {
char c = s.charAt(i);
if(c > 'a' && c < 'z') {
lCount ++;
} else if(c > 'A' && c < 'Z') {
uCount ++;
} else{
oCount ++;
}
SOP(lCount + " " + uCount + " " + oCount);
}
}
还有一种写法如下:
String sL = "qwertyuioplkjhgfdsazxcvbnm";
String sU = "QWERTYUIOPLKJHGFDSAZXCVBNM";
for(int j = 0; j < str.length(); j++) {
char ch = str.charAt(j);
 if(sL.indexOf(ch) != -1) {
  lCount ++;
  } else if(sU.indexOf(ch) != -1) {
  uCount ++;
  } else {
  oCount ++;
 }
}
2、查找字符串中子字符串的个数
public class Demo {
public static void main(String args[]) {
String s = "sunjavawerjava%wrjavaaorcaljavalangjava";
String stf = "java";
int count = 0;
int index = -1;
while((index = s.indexOf(stf)) = -1) {
s = s.substring(index + index.length());
count ++;
}
SOP(count);
}
}
想学好String这个类可以先看API,然后根据API的不断尝试一下每个方法用法,根据你的尝试结果应用在你的需求中!

         

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值