public static void main(String[] args) throws IOException {
BufferedReader input=new BufferedReader(new InputStreamReader(System.in))
System.out.println("输入字符串:")
String str1 = input.readLine()
System.out.print("输入字符:")
String str2 = input.readLine()
char ch = str2.charAt(0)
System.out.println("字符是"+ch)
int count=0
for(int i=0i<str1.length()i++) {
if(ch==str1.charAt(i)){
count++
}
}
System.out.println("字符"+ch+"出现了"+count+"次")
}
}
//如果你只要是否包含的判断
public static void main(String[] args)
{
String str="aab,asds,aa,ab,ba,baba,abbbba"
if(str.indexOf("ba")!=-1){
System.out.println("包含")
}else{
System.out.println("不包含")
}
}
另外:Java中字符串中子串的查找共有四种方法,如下:
1、int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。
2、int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。
3、int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。
4、int lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。
假设你说的第一个字符串是A,第二个是B判断A中是否有一个字符或者一段字符串包含于B中:
boolean ifContrain = false
for(int i = 0 i <A.length - 1 i ++ )
{
for(int j = i + 1 j <A.length j++ )
{
if(B.contains(A.subString(i , j )))
{
ifContrain = true
}
}
}
最后看ifContrain是true,则包含,是false,就是不包含。
如果想要看包含的是哪段,就在ifContrain = true一句后面再加一句 输出 A.subString(i , j ) 就行了。
可以用contains()这个方法,判断一个字符串是否包含另一个字符串。可以用repalce()这个方法,把想删除的字符替换成空。
下面是示例代码,我测试过了,希望能帮到你,仍有问题可以HI我~!
public class Test {
public static void main(String[] args) {
String s1 = "abc"
String s2 = "1111abcdefe"
if(s2.contains(s1)){
System.out.println("s2包含了s1")
//删掉s1
s2 = s2.replace(s2.substring(s2.indexOf(s1), s2.length()), "")
System.out.println(s2)
}else{
System.out.println("s2不包含s1")
}
}
}