判断一个字符串是否是整数

import java.util.Scanner;

public class 判断一个字符串是否是整数 {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		String str = s.nextLine();

		char[] ccc = str.toCharArray();
		// 将字符串里的每个字符放到数组里,也就是说将字符串变成了数组。
		boolean flag = true;
		// for (int i = 0; i < str.length(); i++) {
		// char c = str.charAt(i);//将字符串中的单个字符逐个输出
		// if (!((int) c >= 48 && (int) c <= 57)) {
		// flag = false;
		// break;
		// }
		// }

		for (int i = 0; i < str.length(); i++) {
			int a = (int) ccc[i];
			if (a < 48 || a > 57) {
				flag = false;
				break;
			}
		}
		if (flag) {
			System.out.println(str + "是一个数字");
		} else {
			System.out.println(str + "不是一个数字");
		}
	}
}

字符串比较大小

在这里插入代码片在java编程中,我们会偶尔遇到字符串大小比较的问题,compareTo()方法很简单就实现这种功能。该方法用于判断一个字符串是大于、等于还是小于另一个字符串。判断字符串大小的依据是根据它们在字典中的顺序决定的。
语法:Str1.compareTo(Str2);
其返回的是一个int类型值。若Str1等于参数字符串Str2字符串,则返回0;若该Str1按字典顺序小于参数字符串Str2,则返回值小于0;若Str1按字典顺序大于参数字符串Str2,则返回值大于0。

需要注意的是:
1、java中的compareto方法,返回参与比较的前后两个字符串的asc码的差值,
2、如果两个字符串首字母不同,则该方法返回首字母的asc码的差值;
3、参与比较的两个字符串如果首字符相同,则比较下一个字符,直到有不同的为止,返回该不同的字符的asc码差值,如果两个字符串不一样长,可以参与比较的字符又完全一样,则返回两个字符串的长度差值

public class 字符串比较大小 {
	public static void main(String[] args) {
		System.out.println((int)'a');
		System.out.println((int)'A');
		String s1="12345";
		String s2="222";
		//比较大小,是字符串比较,同数字比较不一样。
	
		System.out.println(s1.compareTo(s2));
	
		String s3="Aello22345";
		String s4="abc222";
		
		System.out.println(s3.compareTo(s4));
		System.out.println(s3.compareToIgnoreCase(s4));
		//忽略大小写
	}
}

判断是否包含子串

字符串的contains方法可以判断一个字符串中是否存在另一个字符子串。

注意:contains方法的参数要求是实现了CharSequence 接口的类,包括CharBuffer, Segment, String, StringBuffer, StringBuilder,不包括字符

如果你想对单个字符用contains方法,可以这样使用:

String Str = “Hello , World .”;
 if (Str.contains(""+‘H’)) {
 System.out.println(“Str contains H”);
 }

用indexOf判断字符串是否中存在指定字符

String Str = “Hello , World .”;
 if (Str.indexOf(‘H’)!=-1) {
 System.out.println(“Str contains H”);
 }
 //indexOf返回的是字符在字符串中的位置,如果不存在则返回-1

代码如下

import java.util.Scanner;

public class 判断是否包含子串 {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		String str = s.nextLine();

		System.out.println(str.startsWith("Hello"));
		System.out.println(str.endsWith("!"));
		System.out.println(str.contains("World"));

		String sss = "llo";
		System.out.println(str.indexOf(sss));
		//判断“llo”在字符串中的索引
	}
}