java 字符串小问题

字符串反转

1转换成char类型数组,倒序取值,拼接

2调用StringBuffer的reverse方法

3使用String的charAt方法,倒序取值,拼接

public class StringTest02 {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		String input = s.next();
//		String reverse = reverse1(input);
//		StringBuffer reverse = reverse2(input);
		String reverse = reverse3(input);
		System.out.println(reverse);
	}

	public static String reverse3(String input) {
		//使用String类的charAt方法,倒序拼接
		String reverse = "";
		for (int i = input.length() - 1; i >= 0; i--) {
			reverse += input.charAt(i);
		}
		return reverse;
	}

	public static StringBuffer reverse2(String input) {
		// StringBuffer的reverse方法
		StringBuffer newStr = new StringBuffer(input);
		newStr.reverse();
		return newStr;
	}

	public static String reverse1(String input) {
		// 转换成char类型数组,倒叙输出拼接,组成一个字符串
		char[] src = input.toCharArray();
		String reverse = "";
		for (int i = src.length - 1; i >= 0; i--) {
			reverse += src[i];
		}
		return reverse;
	}
}

统计字符串中子串出现的次数

1每次获取子串索引,通过从(子串索引+子串长度)处开始截取,得到新子串,再对新子串求索引,截取..如果索引值返回-1则说明无子串存在了,停止,统计索引出现的次数

2每次获取子串在字符串的索引,然后从(子串索引+子串长度)之后的位置求索引,如果返回-1,就停止,统计索引出现的次数

public class StringTest03 {
	public static void main(String[] args) {
		String src = "  hello world and hello orhelloworld";
		String dest = "o";

		int count = countSub2(src, dest);

		System.out.println(count);
	}

	public static int countSub1(String src, String dest) {
		//通过截取子串的方式来获得新串,每次截取的时候从(子串开始的位置+子串长度)开始截取,子串索引值返回-1就停止
		int count = 0;
		int index = 0;
		while ((index = src.indexOf(dest)) != -1) {
			count++;
			src = src.substring(index + dest.length());
		}
		return count;
	}

	public static int countSub2(String src, String dest) {
		//统计索引出现的次数,如果索引值为-1,则停止,每次求索引时要从(当前索引+子串长度)后开始求
		int count = 0;
		int index = 0;
		while ((index = src.indexOf(dest, index)) != -1) {
			count++;
			index += dest.length();
		}
		return count;
	}
}
out:6

统计字符串中大写字母出现的次数

1使用String类的charAt方法,统计每个索引处的元素(char类型)是否在'A'-'Z'之间,若在count++

2转换成char类型数组,统计每个元素是否在'A'-'Z'之间,

public class StringTest04 {
	public static void main(String[] args) {
		String s1 = "Hello WorlD 123 HELLO";

		int count = countBigCase2(s1);
		System.out.println(count);
	}

	public static int countBigCase2(String s1) {
		// 调用String的charAt方法,对每个索引处的元素判断是否在'A'-'Z'之间,若在,count+1
		int count = 0;
		for (int i = 0; i < s1.length(); i++) {
			if (s1.charAt(i) >= 'A' && s1.charAt(i) <= 'Z') {
				count++;
			}
		}
		return count;

	}

	public static int countBigCase(String s1) {
		// 通过转换为char类型数组,统计每个元素是否在'A'-'Z'之间
		char[] c = s1.toCharArray();
		int count = 0;
		for (char i : c) {
			if (i >= 'A' && i <= 'Z') {
				count++;
			}
		}
		return count;
	}
}
out:
8

猜你喜欢

转载自blog.csdn.net/sinat_41132860/article/details/83992111