简体   繁体   English

如何在每个单词中找到第一个字母?

[英]How do I find the first letter in each word?

Where do I edit this code to find the first letter of each word from my input file, keeping the frequency and percentage, rather than every single character? 我在哪里编辑此代码以查找输入文件中每个单词的第一个字母,保留频率和百分比,而不是每个字符? eg where could I implement a charAt(0) or what do I need to change/add? 例如,我在哪里可以实现charAt(0)或我需要更改/添加什么?

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class FirstWordLetters
{
    public static void main(String[] args) throws FileNotFoundException
    {
        char[] capital = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K', 'L', 'M', 'N',
                'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

        char[] small = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };


        //Input Scanner into the system        
        Scanner scan; 
        //2. Locate file using the scanner class - search to computer data location
        try {
            scan = new Scanner(new File("F:/programming principles/Programming Principles - PART B/enciphered.txt"));
        } catch (Exception e) { //throw exception e (meaning prevent any runtime errors)
            System.out.println("File not found");
            return;
        }
        //3. Set up int's (to count, and for the complete count.)
        //the aplhabet has 26 characters so the new int will be 26. The mem. space of the array.
        int[] count = new int[26];
        int completeTotal = 0;
        //4. Start scanning the system
        //Scan every line and notify user that each line has been read properly. 
        //each time line has been read store value in array and increment by one
        while(scan.hasNextLine()) {
            String line = scan.nextLine();
            System.out.println("Line read: " + line);
            char[] digit = line.toCharArray();
            for(int i = 0; i < digit.length; i++) {
                for(int j = 0; j < 26; j++) {

                    if(digit[i] == capital[j] || digit[i] == small[j]) {
                        count[j]++;
                        completeTotal = completeTotal + 1;
                        break;
                    }
                }
            }
        }
        //5. Display results
        //Print the overall data - letter, frequency and percentage.
        System.out.println("");
        System.out.println("First Word Count"); //notify user of what has been counted? (full count)
        for (int i = 0; i < 26; i++) //increment each letter frequency by one each time
        {
            System.out.print(" " + small[i]);
            System.out.print(" " + count[i]);
            //calculate and display percentage for the full count
            if (count[i] > 0)
                System.out.println(" " + (((float) count[i]/completeTotal)*100) + "%");
            else
                System.out.println(" 0%");

        }
    }    
} //end of source code.

This code will do it. 这段代码就可以了。 inputString is your entire file stored as a single string. inputString是整个文件存储为单个字符串。 Also note that if any word begins with a non-alphabetical character it will crash. 另请注意,如果任何单词以非字母字符开头,则会崩溃。 Also, it assumes that every single word is separated with a space or a new line. 此外,它假定每个单词都用空格或新行分隔。

    int[] charCounts = new int[26];

    //Separate the string into individual words
    //The string " /n" tells it to look for spaces and newline characters "/n"
    StringTokenizer st = new StringTokenizer(inputString, " /n");

    //Loop until all the words are processed
    while (st.hasMoreTokens()) {

        //Select the next word
        String word = st.nextToken();

        //Convert the string to upper case so that lower case and upper case characters are represented the same
        word = word.toUpperCase();

        //Get the first character from the word
        char firstChar = word.charAt(0);

        //Convert the character to an integer representing it as an ASCII code
        int charCode = (int) firstChar;

        //Increment the count for that character by 1 
        //(We subtract 65 from the ASCII code because the array starts at 0 but 'A' is at 65)
        charCounts[charCode - 65]++;
    }

    //Obviously replace this section with whatever you like. It's just to show you how to get the values out again.
    for (int i = 0; i < charCounts.length; i++){
        System.out.println((char)(i + 65) + ": " + charCounts[i]);
    }

For the string "asduhasa ioajsdu ijqwjfoscn kopeurfc eqiwdfjs/nijoasdij iohwefscd aosd8ch", this outputs: 对于字符串“asduhasa ioajsdu ijqwjfoscn kopeurfc eqiwdfjs / nijoasdij iohwefscd aosd8ch”,这输出:

A: 2
B: 0
C: 0
D: 0
E: 1
F: 0
G: 0
H: 0
I: 4
J: 0
K: 1
L: 0
M: 0
N: 0
O: 0
P: 0
Q: 0
R: 0
S: 0
T: 0
U: 0
V: 0
W: 0
X: 0
Y: 0
Z: 0

If there's anything you don't understand, I'll do my best to explain it. 如果你有什么不明白的地方,我会尽力解释。

How about using regex? 如何使用正则表达式? Here is a sample .. 这是一个样本..

String line = scan.nextLine();
System.out.println("Line read: " + line);
for(String s : line.split("\\s+")) { 
    System.out.println(s.charAt(0));
    break;
}

Just an excessive use of substring() 只是过度使用substring()

Or you can use charAt() 或者你可以使用charAt()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何给名为word的数组的第一个值赋值? - how do i give a the first letter of an array called word a value? 如何遍历字符串列表以将每个单词的最后一个字母更改为UpCase? - How do I iterate through a list of Strings to change the last letter of each word toUpperCase? 每个单词首字母大写,句子中带有符号 - Capitalize first letter in each word with symbols in sentence 从句子中的每个单词中提取第一个字母 - Extract the first letter from each word in a sentence 打印句子中每个单词的首字母 - Print the first letter of each word of a sentence 如何计算每个单词的字母 - How to count letter of each word 如何将字母从单词的第一个字母移到单词的末尾?然后在末尾添加“ ay” - How can I move a Letter from the first letter of a word to the back of the word?and then adding “ay” to the end 我如何将 Java 中单词的第一个字母大写? - How would I capitalize the first letter of a word in Java? 如何检查单词是否包含一个字母或一组字母? - How do I check to see if a word contains a letter or group of letters? 设计一个比较器来命令单词,使每个单词的最后一个字母是下一个单词的第一个字母? - Designing a comparator to order words so that the last letter of each word is the first letter of the next word?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM