计算字符数非常重要,因为几乎所有依赖用户输入的文本框对插入的字符数都有一定的限制。例如,Facebook帖子的字符限制为63206个字符。而对于Twitter上的推文,字符限制为140个字符,Snapchat的每个帖子的字符限制为80个。
当推特和Facebook帖子更新通过API完成时,确定角色限制变得至关重要。
使用的内置函数
1.文件(字符串路径名):
此功能位于 JAVA伊奥。文件 包裹它通过将给定的路径名字符串转换为抽象路径名来创建一个新的文件实例。
语法:
public File(String pathname)
参数:
pathname - A pathname string
2.FileInputStream(文件):
此功能位于 JAVA伊奥。文件输入流类 包裹 . 它通过打开与文件系统中文件对象文件命名的实际文件的连接来创建FileInputStream。
语法:
public FileInputStream(File file) throws FileNotFoundException
参数:
file - the file to be opened for reading.
抛出:
- FileNotFoundException- 如果文件不存在,是一个目录而不是常规文件,或者由于其他原因无法打开读取。
- 安全例外—— 如果安全管理器存在,并且其checkRead方法拒绝对该文件的读取访问。
3.InputStreamReader(InputStream in):
此功能位于 JAVA伊奥。输入流阅读器 包裹它创建一个使用默认字符集的InputStreamReader。
语法:
public InputStreamReader(InputStream in)
参数:
in - An InputStream
4.BufferedReader(读取器输入):
此功能位于 JAVA伊奥。缓冲区读取 包裹它创建一个缓冲字符输入流,使用默认大小的输入缓冲区。
语法:
public BufferedReader(Reader in)
参数:
in - A Reader
例子:
JAVA
// Java program to count the // number of lines, words, sentences, // characters, and whitespaces in a file import java.io.*; public class Test { public static void main(String[] args) throws IOException { File file = new File( "C:\Users\hp\Desktop\TextReader.txt" ); FileInputStream fileInputStream = new FileInputStream(file); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; int wordCount = 0 ; int characterCount = 0 ; int paraCount = 0 ; int whiteSpaceCount = 0 ; int sentenceCount = 0 ; while ((line = bufferedReader.readLine()) != null ) { if (line.equals( "" )) { paraCount += 1 ; } else { characterCount += line.length(); String words[] = line.split( "\s+" ); wordCount += words.length; whiteSpaceCount += wordCount - 1 ; String sentence[] = line.split( "[!?.:]+" ); sentenceCount += sentence.length; } } if (sentenceCount >= 1 ) { paraCount++; } System.out.println( "Total word count = " + wordCount); System.out.println( "Total number of sentences = " + sentenceCount); System.out.println( "Total number of characters = " + characterCount); System.out.println( "Number of paragraphs = " + paraCount); System.out.println( "Total number of whitespaces = " + whiteSpaceCount); } } |
这个 文本阅读器。txt 文件包含以下数据——
Hello Geeks. My name is Nishkarsh Gandhi. GeeksforGeeks is a Computer Science portal for geeks.
输出:
注: 该程序不会在在线编译器上运行。请在您的系统上创建一个txt文件,并给出在您的系统上运行该程序的路径。
本文由 马扬克·库马尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论。