Question

Write a program whose input is a character and a string, and whose output indicates the...

Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string. Ex: If the input is: n Monday, the output is: 1 Ex: If the input is: z Today is Monday, the output is: 0 Ex: If the input is: n It's a sunny day, the output is: 2 Case matters. Ex: If the input is: n Nobody, the output is: 0 n is different than N..

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.Scanner;

public class LabProgram {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        char ch = in.next().charAt(0);
        String line = in.nextLine();
        int count = 0;
        for (int i = 0; i < line.length(); ++i) {
            if (line.charAt(i) == ch) {
                ++count;
            }
        }
        System.out.println(count);
    }
}

#include <iostream>
#include <string>

using namespace std;

int main() {
    char ch;
    string str;
    int count = 0, i;   // initialize count to 0
    cin >> ch;  // read a character
    getline(cin, str);  // read rest of the line
    for (i = 0; i < str.size(); ++i) {  // go through all characters of line
        if (str[i] == ch) { // if character is same as the first character entered
            ++count;    // then increase count by 1
        }
    }
    cout << count << endl;  // print count
    return 0;
}

if __name__ == '__main__':
    input_string = input()
    char = input_string[0]
    count = 0
    for ch in input_string[1:]:
        if ch == char:
            count += 1
    print(count)

Add a comment
Know the answer?
Add Answer to:
Write a program whose input is a character and a string, and whose output indicates the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT