Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added Findcharinstring #38

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions findcharinstring.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*Java program to find the occurrence of a character in a string */
class JavaExample {

static void countEachChar(String str)
{
//ASCII values ranges upto 256
int counter[] = new int[256];

//String length
int len = str.length();

/* This array holds the occurrence of each char, For example
* ASCII value of A is 65 so if A is found twice then
* counter[65] would have the value 2, here 65 is the ASCII value
* of A
*/
for (int i = 0; i < len; i++)
counter[str.charAt(i)]++;

// We are creating another array with the size of String
char array[] = new char[str.length()];
for (int i = 0; i < len; i++) {
array[i] = str.charAt(i);
int flag = 0;
for (int j = 0; j <= i; j++) {

/* If a char is found in String then set the flag
* so that we can print the occurrence
*/
if (str.charAt(i) == array[j])
flag++;
}

if (flag == 1)
System.out.println("Occurrence of char " + str.charAt(i)
+ " in the String is:" + counter[str.charAt(i)]);
}
}
public static void main(String[] args)
{
String str = "beginnersbook";
countEachChar(str);
}
}