Searching for specific character in string with static method - java

I have to make a program that counts the number of the letter B in a string. I got that part already, but it also requires me to use a static method that returns true or false based on if the string has any Bs in it and i really don't see how to fit that part in.
import java.util.Scanner;
public class CountB {
// write the static method “isThisB” here
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a string: ");
String w = keyboard.nextLine();
int count=0;
for (int i=0; i<w.length(); i++)
{
if (w.charAt(i)=='B'||w.charAt(i)=='b')
{
count++;
}
}
System.out.println("Number of B and b: "+ count);
}
}

private static boolean hasAnyB(String str) {
return str.contains("B") || str.contains("b");
}

Something like this:
static boolean check(String str){
if(str.indexOf('B')>0 || str.indexOf('b')>0 )
return true;
else
return false;
}

Use the built-in matches() method, which uses regex:
private static boolean hasB(String str) {
return str.matches(".*[bB].*");
}
Using regex is a near way to handle mixed case issues.

Just Deploy all coding inside a static method that's it
public static void main(String[] args)
{
methodOne("Pass string over here");
}
public static boolean methodOne(String s)
{
return s.contains("B");
}

To get the count of b or B you can do
int bCount = w.replaceAll("[^Bb]", "").length();
If you have to use a hasB method you could do it like this, though its pretty inefficient and longer than it needs to be
int count = 0;
for(String ch: w.split("")) // one character at a time.
if(hasB(ch))
count++;

private static boolean hasAnyB(String str) {
return str.toLowerCase().contains("b");
}

The easiest i could think.
static boolean isThisB(String s, int count) {
for(int i=0; i<s.lenght(); i++) {
char c = s.charAt(i);
if(c == 'b' || c == 'B')
count ++;
}
return count > 0;
}

Related

Why is this logic wrong for Integer palindrome

Refer below Java code for palindrome.
This is to check if the code logic is right or wrong
/* Please expalin why this logic is wrong*/
public class IntegerIsPalindrome {
public static boolean numPalindrome(int x){
String ParseNum = Integer.toString(x);
int lenPar = ParseNum.length();
for(int i = 0 ; i < ParseNum.length();i++){
if(ParseNum.charAt(0) != ParseNum.charAt(lenPar -1 -i)){
return false;
}
}
return true;
}
public static void main(String args[]){
boolean result = numPalindrome(323);
System.out.println(result);
}
}
It's because you always compare the first character. Specifically:
ParseNum.charAt(0)...
You should change this to:
ParseNum.charAt(i)...
Looking into 323, the first character, '3', and the last, '3', is compared. Then, the first '3' is compared with the '2', resulting in false.
You should iterate loop upto ParseNum.length()/2 is enough.
Ex: If value is 12321,
you should check
charAt[0] with charAt[4] means 1=1
charAt[1] with charAt[3] means 2=2
for(int i = 0 ; i < ParseNum.length()/2;i++){
if(ParseNum.charAt(i) != ParseNum.charAt(lenPar -1 -i)){
return false;
}
}
you should need to change ParseNum.charAt(0) in the for loop into ParseNum.charAt(i)
Here the code you can find palindrome easily:
package com.company;
import java.util.Scanner;
public class Palindrome
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Input: ");
String input = scanner.next();
System.out.println(isPalindrome(input) ? "palindrome" : "not a palindrome");
}
private static boolean isPalindrome(String input)
{
String temp = "";
for (int i = input.length() - 1; i >= 0; i--)
{
temp += input.charAt(i);
}
return input.equalsIgnoreCase(temp);
}
}

Recursive String Parser

I need to create a program that recursively parses a string into smaller substrings. Every substring is one letter shorter than the previous; once it's at the end it would redisplay the word, but with the first letter sliced off, and then substrings of that.
For example: Given the word 'Slugger' the program would display
Slugger
Slugge
Slugg
Slug
Slu
Sl
S
lugger
lugge
lugg
lug
lu
l
And on and on.
This is part of my code so far that is supposed to break things up:
private static void stringParser(String str)
{
if(str.length() < 1)
{
return;
}
else if(str.length() == 0)
{
removeFirstChar(str, 1);
}
else
{
System.out.println(str);
stringParser(str.substring(0, str.length() - 1));
}
} // End stringParser method
private static void removeFirstChar(String str, int i)
{
String strNew = str.substring(i);
stringParser(strNew);
return strNew;
} // End removeFirstChar method
I think I've got all the pieces and parts that I need, but perhaps just don't have them in the right order to do what I want.
Any help is greatly appreciated.
Thank you!
I have added the following in your code. See if this works
public static void main(String[] args) {
String str = "slugger";
for(int i=0;i<str.length();i++) {
stringParser(str.substring(i));
}
}
Complete code.....
public class Test {
public static void main(String[] args) {
String str = "slugger";
for(int i=0;i<str.length();i++) {
stringParser(str.substring(i));
}
}
private static void stringParser(String str)
{
if(str.length() < 1)
{
return;
}
else if(str.length() == 0)
{
removeFirstChar(str, 1);
}
else
{
System.out.println(str);
stringParser(str.substring(0, str.length() - 1));
}
} // End stringParser method
private static void removeFirstChar(String str, int i)
{
String strNew = str.substring(i);
stringParser(strNew);
str = strNew;
}
}

How can I check character occurrence in a string?

My Question is-
Input is string. Return true if the String has exactly 1 character that appears twice in the string, 0 character that appear thrice in the string, and at least 1 character that appear four or more times in the string. There is a problem in my code and I am unable to find out the problem.
public class CheckCharacterOccurence {
static String testcase1 = "jjiiiiyy";
public static void main(String[] args) {
CheckCharacterOccurence testInstance = new CheckCharacterOccurence();
boolean result = testInstance.checkCharacterOccurence(testcase1);
System.out.println(result);
}
public boolean checkCharacterOccurence(String str) {
char ch=' ';
char ch1=' ';
int temp=0;
int temp1=0;
int temp2=0;
int count=0;
for(int i=0;i<str.length();i++){
ch=str.charAt(i);
for(int j=i;j<str.length();j++){
if(str.charAt(i)==str.charAt(j)){
ch1=str.charAt(i);
count++;
}
}
System.out.println(count);
if(count==2&&ch!=ch1){
temp++;
}
if(count==3&&ch!=ch1){
temp1++;
}
if(count>=4){
temp2++;
}
count=0;
}
if(temp==1&&temp1==0&&temp2>=1){
return true;
}
return false;
}
}
I would suggest using a map
For all characters in string, increment map[that_char]
At last iterate over map to find how many times each character appeared.
Alternatively you can use array also to keep count.
Something like
int [] ctr = new int[256]
ctr = all zeroes
for (ch : string)
ctr[ch]++
mxocc = 0
maxch = 'a'
for(ch = a, b, c, d, e...)
if(ctr[ch] > maxocc) maxocc = ctr[ch] and maxch = ch
Output require info
hey you can figure out the problem ... atleast i can give to some extend same code , you can check it and try to solve your problem... This program finds the pattern in the string, now you can go through this program, and try to solve ur problem in your program by your own self.and try to do it by your own then only ur coding skills will get improved.and vote this answer if u fing it really helpful
#include<stdio.h>
#include<string.h>
int occur(char[],char[]);
int occur(char sent[],char pattern[])
{
int count=0;
for(int i=0,j=i;sent[i]!='\0';)
{
if(sent[i+j]==pattern[j]&&pattern[j]!='\0')
{
j++;
}
else if(j==strlen(pattern))
{
count++;
i=i+j;
j=0;
}
else
{
i++;
j=0;
}
}
return count;
}
int main()
{
char sent[] = "aabaabaaabbbabababddfggaabbbasab";
char pattern[] = "aba";
int result = occur(sent,pattern);
printf("\nNo of Occurrences --- > %d",result);
return 0;
}
You should simplify your code. For example there is not need to use those complex for-loops, you can use a for-each.
This code finds out the frequency of characters in a string and stores it in a Map.
import java.util.*;
public class CheckCharacterOccurence {
public static void main(String[] args) {
Map<Character, Integer> counting = new HashMap<Character, Integer>();
String testcase1 = "Helloooo";
for(char ch: testcase1.toCharArray()){
Integer freq = counting.get(ch);
counting.put(ch, (freq == null) ? 1 : freq + 1);
}
System.out.println(counting.size() + " distinct characters:");
System.out.println(counting);
}
}

Repeating a string

I am very new to programming and I have to write a method and program for the following; public static String repeat(String str, int n) that returns the string repeated n times. Example ("ho", 3) returns "hohoho" Here is my program so far:
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
System.out.println(repeat (str));//Having trouble with this line
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return ""//Having trouble with this line
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
I made some changes to my code, but it still is not working
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
int n = in.nextInt();
System.out.println(repeat(str,n));
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return "";
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
You've missed a semi colon on the line you're having trouble with, it should be return ""; and not return ""
Also, the line System.out.println(repeat (str)); should have 2 arguments because you're repeat definition is:
public static String repeat(String str, int n)
As a further note, an easier function might be
public static String repeat(String str, int n)
{
if (n == 0) return "";
String return_str = "";
for (int i = 0; i < n; i++)
{
return_str += str;
}
return return_str;
}
public static String repeat(String toRepeat, int n){
if(n==0){
return "";
}
return toRepeat+repeat(toRepeat,n-1);
}
2 things I noticed quickly: you forgot a semi-column and your call of "repeat" doesn't match the method signature (you forgot n)
You are not passing correct arguments while you calling the desired method.
Call as repeat (str,k) k - should be an integer

Counting the spaces in a string

I want to count the spaces in a string:
public class SongApp {
public static void main(String[] args) {
String word = "a b c";
int i =0,spaceCount=0;
while(i<word.length()){
char temp = word.charAt(i);
System.out.println(temp);
if(" ".equals(temp)){
spaceCount++;
}
i++;
}
System.out.println("Spaces in string: "+spaceCount);
}
}
When I replace the if statement with if(temp.equals(" ")), I get a "cannot invoke(String) on the primitive type char.
I don't understand why this won't work.
It won't work because you are calling a method of Class String (equals()) on a value which is of primitive type 'char'. You are trying to compare a 'char' with a 'String'.
You must compare between 'char's and since it's a primitive value you need to use '==' boolean compare operator like:
public class SongApp {
public static void main(String[] args) {
String word = "a b c";
int i = 0,
spaceCount = 0;
while( i < word.length() ){
if( word.charAt(i) == ' ' ) {
spaceCount++;
}
i++;
}
System.out.println("Spaces in string: "+spaceCount);
}
}
You can use the replace function for String to replace all the spaces(" ") with no spaces("") and get the difference between the lengths before and after calling the replace function.
Go through this example:
class Test{
public static void main(String args[]){
String s1 = "a b c";
int s1_length = s1.length();
System.out.println(s1_length); // 5
String s2 = s1.replace(" ","");
int s2_length = s2.length();
System.out.println(s2_length); // 3
System.out.println("No of spaces = " + (s1_length-s2_length)); // No of spaces = 2
}
}
You can use commons-lang.jar to calculate this.
`public class Main {
public static void main(String[] args) {
String word = "a b c";
System.out.println("Spaces in string: " + StringUtils.countMatches(word," "));
}
}`
The source of "StringUtils.countMatches" is below:
public static int countMatches(String str, String sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) {
count++;
idx += sub.length();
}
return count;
}
public class CountSpace {
public static void main(String[] args) {
String word = "a b c";
String data[];int k=0;
data=word.split("");
for(int i=0;i<data.length;i++){
if(data[i].equals(" ")){
k++;
}
}
System.out.println(k);
}
}

Categories

Resources