Repetition of a word in String with out using collections - java

Can any one suggest me to write a logic for this without using collections.
I have a string s="This is the place called island and it is a nice place ";
Input String to find repetition word is: "is";
output should be : 4

You can follow the below logic to do it.
Split the String on whitespace.
Initialize an integer counter to 0.
Traverse through each of the elements of the resultant array and for each String element of the array, do the following:
a) If stringElement.contains("is"), increment the counter created in step 2.
b) If !stringElement.contains("is"), do nothing and move on to the next element.
Do this till you exhaust all the elements of the array.
Print the counter value.
Try to write the code for this on your own and get back here if you're stuck up anywhere.

As simple as
int count = 0;
for (int startIndex = 0; startIndex >= 0; startIndex = str.indexOf("is", startIndex)) {
count++;
}

Use the following method, it should work:
public static int countSubStrings(String subString, String mainString){
return (mainString.length() - mainString.replace(subString, "").length()) / subString.length();
}

string s="This is the place called island and it is a nice place ";
s = s+" ";
System.out.println(s.split("is").length-1);

you can use this. Hope you are using Java.
public static void main(String[] args) {
String str = "This is the place called island and it is a nice place";
Pattern pattern = Pattern.compile("is");
Matcher matcher = pattern.matcher(str);
int count = 0;
while (matcher.find())
count++;
System.out.println(count); // prints 4
}

this method will count how many time s2 appears in s1
public static int CountStr(String s1,String s2){
int cnt=0,temp=0;
if(s1.indexOf(s2)>0){
temp=s1.indexOf(s2);
cnt++;
}
while(s1.indexOf(s2,temp+1)>0){
cnt++;
temp=s1.indexOf(s2,temp+1);
}
return cnt;
}

Related

String printed out over multiple lines

I am not very good at java so that's why some things might not make sense at all. I was just simply using code from bits I found online which I know is wrong.
My current issue is that it simply prints a blank code; I am not sure how to get it to print it like so:
Input:
APPLE
Output:
A
AP
APP
APPL
APPLE
Current Code:
import java.util.Scanner;
public class WordGrow
{
public static void main(String[]args)
{
//take your word input
//enter word as a parameter in WordGrow()
System.out.println("Please enter the word to *GROW*");
Scanner scan = new Scanner(System.in);
String theword = scan.next();
System.out.println(makeTree(theword, theword.length()));
}
public static String makeTree(String word, int len)
{
int count = 0;
//start with the first letter and print
//and add another letter each time the loop runs
if (word.length() > 0)
{
for(int i = 0; i < word.length();i++)
{
return word.substring(0, i++);
}
}
return (word.charAt(1) + makeTree(word, len));
}
}
Take Java out of it. Let's take this back to pen and paper.
First, look at the pattern you're printing out. How would you print out just one letter of that string? How would you print out two?
Let's start with that approach. Let's try to print out one letter in that string.
public void printStringChain(String word) {
System.out.println(word.substring(0, 1));
}
What about two letters?
public void printStringChain(String word) {
System.out.println(word.substring(0, 2));
}
What about word.length() letters?
public void printStringChain(String word) {
System.out.println(word.substring(0, word.length()));
}
The main thing I'm trying to get you to see is that there's a pattern here. In order to accomplish this, you likely need to go from zero to the length of your string in order to print out each line on its own.
Here's a start. I leave figuring out the nuance and barriers inside of the substring as an exercise for the reader.
public void printStringChain(String word) {
for (int i = 0; i < word.length(); i++) {
// the question mark relates to i, but in what way?
System.out.println(word.substring(0, (?)));
}
}
If recursion is not compulsory, you could simply iterate through the given String:
String str = "APPLE";
for(int x=0; x<str.length(); x++){
System.out.println(str.substring(0, x+1));
}
Output:
A
AP
APP
APPL
APPLE
One cannot return multiple times, at the first moment the result is passed on to the caller.
For String there is a buffering class for efficiency, the StringBuilder.
Including the empty string that would be:
public static String makeTree(String word) {
StringBuiilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++){
sb.append(word.substring(0, i));
sb.append("\r\n");
}
return sb.toString();
}
It uses the Windows end-of-line characters CR+LF aka \r\n.
You can make that platform independent, but you get the idea.
WITH RECURSION
public static String makeTree(String word)
{
if (word.length() <= 1){
return word;
}
return makeTree(word.subSequence(0, word.length()-1).toString()) + System.lineSeparator() + word;
}

Recursively finding indices of a string

I'm trying to write a code that returns an Array whose elements are the indices of the word(occurences) that I'm looking for in a string :
ex)
d
Input:
String sent = "Hi is Hi is Hi is";
String find = "Hi";
ArrayList<Integer> index = indexFinder(sent,find);
For(int i=0;i<index.size(),i++)
System.out.println(index.get(i));
Output:
0
6
12
It would be very nice if Java had a string slicing function like python.. but since it does not.. I tried to use substring() method.
import java.util.ArrayList;
public class recursionEx {
ArrayList<Integer> index = new ArrayList<Integer>();
ArrayList<Integer> indexFinder(String sent, String find){
int pos =0;
int subPos =0;
if(sent.contains(find)==false){
return index;
}
else if(sent.contains(find)){
pos = sent.indexOf(find);
index.add(pos);
subPos = pos+find.length();
return indexFinder(sent.substring(subPos),find);
}
return index;
}
public static void main(String[] args) {
String sent = "Hi is Hi is Hi is";
String find = "Hi";
recursionEx r = new recursionEx();
ArrayList<Integer> g = r.indexFinder(sent, find);
for(int i=0;i<g.size();i++){
System.out.println(g.get(i));
}
}
}
the output was
0
4
4
In hindsight, I'm gettng the substring of the original String sent every iteration, thus elements in index Array are the indices of the String find in substring of String sent which are 0,4,4.
How can I fix this to get the desired output?
Any help is appreciated!
You should not use the substring as parameter, but only the start of the search in the string. Here is a way that works, it is not perfect, try to make it better :
import java.util.ArrayList;
public class recursionEx {
ArrayList<Integer> index = new ArrayList<Integer>();
String string;
recursionEx(String string){this.string = string;}
ArrayList<Integer> indexFinder(int position, String find){
int pos =0;
int subPos =0;
if(string.substring(position).contains(find)==false){
return index;
}
else if(string.substring(position).contains(find)){
pos = string.substring(position).indexOf(find) + position;
index.add(pos);
subPos = pos+find.length();
return indexFinder(subPos,find);
}
return index;
}
public static void main(String[] args) {
String sent = "Hi is Hi is Hi is";
String find = "Hi";
recursionEx r = new recursionEx(sent);
ArrayList<Integer> g = r.indexFinder(0, find);
for (Integer pos : g)
System.out.println(pos);
}
}
Add the length of the former substring to each following output, then you get the correct numbers. You can calculate these lengths by the older indices.
You don't have to use recursion to find the indices of substrings but rather use indexOf(searchstring, offset) until you don't find the search string anymore.
Alternatively use regex, i.e. Pattern and Matcher and collect the group(0) indices.
Edit:
Since you want to use recursion you could change the loop into recursive calls. In that case you could just pass the offset to the recursive call as well and keep using indexOff(find, offset).
If you want to do it using substring() you'd also have to keep track of the substring's position in the original string and add that to the results of indexOf(find), otherwise you get the indices relative to the substring only.

Find first occurrence of any symbol of string in other string

I have a problem: I need to find first occurrence of any symbol from string s2 (or array of char) in string s1.
Is there standard function for this purpose? If there isn't, whats the good implementation for this problem? (Of course I can run indexOf for every char from my s2, but this does't seem like a good algorithm, because if only the last symbol occurs in s1, we must run through s1 |s2|-1 times before I get an answer).
Thank you very much!
Put all characters from s2 into a constant-time lookup data structure (e.g. HashSet). Iterate over each character in s1 and see if your data structure contains that character.
Roughly (untested):
public int indexOfFirstContainedCharacter(String s1, String s2) {
Set<Character> set = new HashSet<Character>();
for (int i=0; i<s2.length; i++) {
set.add(s2.charAt(i)); // Build a constant-time lookup table.
}
for (int i=0; i<s1.length; i++) {
if (set.contains(s1.charAt(i)) {
return i; // Found a character in s1 also in s2.
}
}
return -1; // No matches.
}
This algorithm is O(n) as opposed to O(n^2) in the algorithm you describe.
Using regex:
public static void main(final String[] args) {
final String s1 = "Hello World";
final String s2 = "log";
final Pattern pattern = Pattern.compile("[" + Pattern.quote(s2) + "]");
final Matcher matcher = pattern.matcher(s1);
if (matcher.find()) {
System.out.println(matcher.group());
}
}
What you are looking for is indexOfAny from Apache StringUtils.
It looks like the implementation is:
public static int indexOfAny(String str, char[] searchChars) {
if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
return -1;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
for (int j = 0; j < searchChars.length; j++) {
if (searchChars[j] == ch) {
return i;
}
}
}
return -1;
}
What is meant by symbol in this context? If it's just a 16-bit Java char, it's easy. Make a lookup table (array) for all possible values, indicating whether they appear in s2. Then step through s1 until either you've found a symbol from s2 or you've reached the end of s1. If a symbol is a Unicode code-point, it's more complicated, but the above gives a method to find out where you need to take a closer look.

How should I count the number of occurrences of a character at the beginning of a string in Java

I have a string similar to this ,,,foo,bar and I need to count the amount of "," at the beginning of the string in java any ideas?
Have a counter variable which counts the number of occurrences. Then loop through the entire String, using charAt(i) to get the char at position i. Test to see if it's equal to charAt(0). If it is, increment counter and if it isn't, break out of the loop.
Take a look at the String javadoc. It contains methods you can use to get the length of the String and get characters at certain positions.
If starting characters are known then build a regex pattern and get the first group. First group string will contain the exact match of desired sequence, length of this string is the resultant count.
You can also use regexp:
public static int countCommasAtBegin(String str) {
Matcher commas = Pattern.compile("^,*").matcher(str);
if (commas.find()) {
return commas.group().length();
} else {
return 0;
}
}
but for such trivial task I prefer to use simple loop.
A simple loop (while or for) containing a if with a condition of equality that increments a counter if true should be enough.
This quick-n-dirty solution worked for me.
public static void main(String[] args)
{
String s = ",,,foo,bar";
int count = 0;
for (int i = 0; i < s.length() ; i++) {
if (s.charAt(i) != ',')
break;
count++;
}
System.out.println("count " + count);
}
Update: just realized that you only need to count the ',' at the beginning of the string and not the middle. I've updated the code to do that.
If you don't want to use any any external jars just write a simple function:
public static int countAtBegin(String str, char c) {
for (int ret = 0; ret < str.length(); ret++) {
if (str.charAt(ret) != c)
return ret;
}
return str.length();
}

Java function for counting word

Is there any default method in Java that can count total occurrence of a word? For example, how many times stack occurred in a string "stack is stack".
Edit: please only Java no third party library.
You can use StringUtils.countMatches(string, "stack") from commons-lang. This doesn't account for word boundaries, so "stackstack" will be counted as two occurences.
There is no built-in .matchCount() method. Here is my impl.
public static int matchCount(String s, String find) {
String[] split = s.split(" ");
int count = 0;
for(int i=0; i<split.length; i++){
if(split[i].equals(find)){
count++;
}
}
return count;
}
String s = "stack is stack";
System.out.println(matchCount(s, "stack")); // 2
You could use:
public static int NumTimesInString(String target, String regex)
{
return (" " + target + " ").split(regex).length - 1;
}
This will work so long as regex doesn't match a beginning or ending space... Hmm, this might not work for some cases. You might be better writing a function which uses indexOf
public static int NumTimesInString(String target, String substr)
{
int index = 0;
int count = -1;
while (index != -1)
{
index = target.indexOf(substr, index);
count++;
}
return count;
}
NOTE: not tested
Either one can be used as:
int count = NumTimesInString("hello world hello foo bar hello", "hello");
// count is 3

Categories