Java使用charAt(i)方法查看字符串Stringstr=“ab#cd#de#”中有多少个#
时间: 2024-05-05 22:21:27 浏览: 15
可以使用如下代码来查看字符串中有多少个#:
```java
String str = "ab#cd#de#";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '#') {
count++;
}
}
System.out.println("字符串中有 " + count + " 个 #");
```
运行结果为:
```
字符串中有 3 个 #
```
相关问题
在java语言中,判断一个字符串中每一个字符是否为#,怎样表达
在Java语言中,可以使用for循环遍历字符串中的每一个字符,然后判断该字符是否为#。具体实现如下:
```
String str = "###";
boolean allHash = true;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != '#') {
allHash = false;
break;
}
}
if (allHash) {
System.out.println("The string contains only # characters");
} else {
System.out.println("The string contains at least one non-# character");
}
```
上面的代码中,用一个boolean类型的变量allHash来记录字符串中的每一个字符是否都为#,初始值为true。然后使用for循环遍历字符串中的每一个字符,如果发现其中有一个字符不为#,就将allHash设为false,并且跳出循环。最后根据allHash的值输出相应的结果。
java统计字符串str1中字符串str2出现的次数,不使用index方法
可以使用循环遍历的方式,逐个比较str1中的字符是否与str2相同,如果相同则累加出现次数。代码示例如下:
```
public static int countSubstring(String str1, String str2) {
int count = 0;
int str1Len = str1.length();
int str2Len = str2.length();
for (int i = 0; i <= str1Len - str2Len; i++) {
boolean flag = true;
for (int j = 0; j < str2Len; j++) {
if (str1.charAt(i + j) != str2.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
count++;
}
}
return count;
}
```
这样就可以统计出字符串str1中字符串str2出现的次数了。