已知字符串,统计该字符串个数java
时间: 2023-07-16 13:14:04 浏览: 53
不太清楚您的问题具体是什么,但是如果您是想要统计一个字符串中某个字符出现的次数,可以使用以下代码:
```java
String str = "hello world";
char c = 'l';
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
System.out.println("字符 " + c + " 出现的次数为:" + count);
```
如果您是想要统计一个字符串中不同字符的个数,可以使用以下代码:
```java
String str = "hello world";
int count = 0;
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < str.length(); i++) {
set.add(str.charAt(i));
}
count = set.size();
System.out.println("不同字符的个数为:" + count);
```
如果您有其他问题,请提供更详细的信息。
相关问题
java中如何把一个已知的字符串数组转为字符串
在 Java 中,可以使用 `String.join()` 方法将一个已知的字符串数组转换为字符串。
例如:
```
String[] arr = {"apple", "banana", "cherry"};
String str = String.join(", ", arr);
```
此代码将创建一个字符串:`"apple, banana, cherry"`。
java取字符串中第一个出现已知字符的后一段字符串,请给出示例代码
以下是示例代码:
```java
public class Main {
public static void main(String[] args) {
String str = "Hello, world!";
char ch = ',';
int index = str.indexOf(ch);
if (index != -1) {
String result = str.substring(index + 1);
System.out.println(result); // 输出 " world!"
}
}
}
```
在这个示例中,我们首先定义了一个字符串 `str` 和一个字符 `ch`,然后使用 `indexOf()` 方法查找字符串 `str` 中第一次出现字符 `ch` 的位置。如果找到了,我们就使用 `substring()` 方法从该位置的下一个字符开始提取子字符串,最后将结果输出到控制台。注意,`substring()` 方法的参数是子字符串的起始位置,所以我们需要将 `index` 加 1。