我在这里尝试做的是读取一个文件并计算每个字符。每个字符都应该为“int count”添加+1,然后打印出“int count”的值。
我希望我想要做的事情很明确。
{{1}}
答案 0 :(得分:3)
转到下一个标记
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext()) {
count = count + (cCount.next()).length();
}
答案 1 :(得分:1)
使用java 8 Stream API,您可以按照以下方式执行
package example;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CountCharacter {
private static int count=0;
public static void main(String[] args) throws IOException {
Path path = Paths.get("greeting");
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
count = lines.collect(Collectors.summingInt(String::length));
}
System.out.println("The number of charachters is "+count);
}
}
答案 2 :(得分:0)
好吧,如果您正在寻找一种方法,只计算所有字符和整数,而没有任何空格和类似&#39; tab&#39;,&#39;输入&#39;等等。然后你可以先用这个函数删除那些空格:
st.replaceAll("\\s+","")
然后你会做一个字符串计数
String str = "a string";
int length = str.length( );
答案 3 :(得分:0)
首先,为什么不使用try { }
catch(Exception e)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("greetings.txt"));
String line = null;
String text = "";
while ((line = reader.readLine()) != null) {
text += line;
}
int c = 0; //count of any character except whitespaces
// or you can use what @Alex wrote
// c = text.replaceAll("\\s+", "").length();
for (int i = 0; i < text.length(); i++) {
if (!Character.isWhitespace(text.charAt(i))) {
c++;
}
}
System.out.println("Number of characters: " +c);
} catch (IOException e) {
System.out.println("File Not Found");
} finally {
if (reader != null) { reader.close();
}
}