JAVA基本数据类型和String类总结

1、基本数据类型有8种:byte int long short float double boolean char
2、String类
.定义字符串变量的两种方法:
String 字符串名="字符串";
String 字符串名=new String("字符串");

.定义字符数组的方法:
char[] 数组名={'单个字符','单个字符','单个字符'};

.如何获取指定的索引位置的字符?
答:char 字符名=字符串名.charAt(i); //i为指定索引位置

.如何比较两个字符串是否相等?
答: 字符串1.equals(字符串2) 的值为真,说明两个字符串相等。

.如何判断某个字符串是否包含在另一个字符串中?
答: 字符串1.contains(字符串2) 的值为真,说明字符串1中包含字符串2。

.如何去掉包含的字符串?
答: 字符串1.replace(字符串2,"")//将字符串1中包含的字符串2用空格代替。

.如何根据字符串2(包含于字符串1中)将字符串1拆分?
答:字符串1.split(字符串2)

.如何找到某个字符第一次出现的位置?
答: 字符串名.indexOf("字符名");

.String.valueOf(参数); 是什么意思?
答:valueOf()方法旨在将参数原本的类型转化为String类型。例如,int a=1000; String.valueOf(a); 就实现了把a从整型转化为String类型的功 能。

.练习:统计给定字符串中每个字符出现的次数
自己写的代码:
public class tongjizifu {

/**
* 定义一个string的使用类
* @param args
*/
public static void main(String[] args) {
//定义字符串变量

String str1="aaabbbbccccc";

for(int i=0;i<str1.length();i++){
int k=1;
char c=str1.charAt(i);
for (int j=0;j<str1.length();j++){

char b=str1.charAt(j);
if(c==b&&i!=j){
k++;
b='\0';
}

}
System.out.println("字符"+c+"出现的次数为:"+k);

//将统计后的字符全部替换为空
str1=str1.replace(str1.charAt(i)+"","");

}


}

}
// TODO Auto-generated method stub

给出的两种实现统计字符的函数:
package cn.netjava.lesson01;

public class StringPractise {

/**
* @param args
*/
public static void main(String[] args) {
// 实例化一个接受命令行输入信息的对象
java.util.Scanner sc = new java.util.Scanner(System.in);

// 实例化StringPractise类的对象
StringPractise sp = new StringPractise();
System.out.println("请输入要统计的字符串:");
// 获取输入的一行字符串
String temp = sc.nextLine();
System.out.println("开始使用第一种方式统计.");

//调用第一种统计的方式
sp.wayOne(temp);

System.out.println("请输入要统计的字符串:");
// 获取输入的一行字符串
temp = sc.nextLine();
System.out.println("开始使用第二种方式统计.");
// 调用第二种统计的方式
sp.wayTwo(temp);

}

/**
* 第一种统计方式 根据ascii和数组来实现
*/
public void wayOne(String temp) {
// 定义一个存储统计次数的数组
int[] array = new int[256];
// 循环遍历字符串
for (int i = 0; i < temp.length(); i++) {
// 获取指定索引位置的字符
char c = temp.charAt(i);
// 将字符转换为对应的ascii
int ascii = c;
// 将对应的ascii位置的数组元素加1
array[ascii]++;
}

// 输出
for (int i = 0; i < array.length; i++) {
// 如果统计个数部位0则输出
if (array[i] != 0) {
char c = (char) i;
System.out.println("字符" + c + "出现的次数是" + array[i]);
}
}
}

/**
* 第二种统计方式 根据replace方法来实现
*/
public void wayTwo(String temp) {
// 循环遍历字符串
for (int i = 0; i < temp.length();) {
int count = 1;// 计数器
// 循环遍历字符串,从i+1的基础上开始,让i位置的每一个字符都与后边的字符进行比较
for (int j = i + 1; j < temp.length(); j++) {
// 如果相等
if (temp.charAt(i) == temp.charAt(j)) {
// 计数器加1
count++;
}
}
System.out.println("字符" + temp.charAt(i) + "出现的次数是" + count);
// 将相同的字符全部都替换为空
temp = temp.replace(temp.charAt(i) + "", "");
}

}

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值