This question already has answers here:
Find the Number of Occurrences of a Substring in a String
(27 answers)
Closed 5 years ago.
String str = "ABthatCDthatBHthatIOthatoo";
System.out.println(str.split("that").length-1);
From this I got 4. that is right but if last that doesn't have any letter after it then it shows wrong answer '3' as in :
String str = "ABthatCDthatBHthatIOthat";
System.out.println(str.split("that").length-1);
I want to count the occurrence of "that" word in given String.
You could specify a limit to account for the final 'empty' token
System.out.println(str.split("that", -1).length-1);
str.split("that").length doesn't count the number of 'that's . It counts the
number of words that have 'that' in between them
For example-
class test
{
public static void main(String args[])
{
String s="Hi?bye?hello?goodDay";
System.out.println(s.split("?").length);
}
}
This will return 4, which is the number of words separated by "?".
If you return length-1, in this case, it will return 3, which is the correct count of the number of question marks.
But, what if the String is : "Hi????bye????hello?goodDay??"; ?
Even in this case, str.split("?").length-1 will return 3, which is the incorrect count of the number of question marks.
The actual functionality of str.split("that //or anything") is to make a String array which has all those characters/words separated by 'that' (in this case).The split() function returns a String array
So, the above str.split("?") will actually return a String array : {"Hi,bye,hello,goodDay"}
str.split("?").length is returning nothing but the length of the array which has all the words in str separated by '?' .
str.split("that").length is returning nothing but the length of the array which has all the words in str separated by 'that' .
Here is my link for the solution of the problem link
Please tell me if you have any doubt.
Find out position of substring "that" using lastIndexOf() and if its at last position of the string then increment the cout by 1 of your answer.
Try this
String fullStr = "ABthatCDthatBHthatIOthatoo";
String that= "that";
System.out.println(StringUtils.countMatches(fullStr, that));
use StringUtils from apache common lang, this one https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/src-html/org/apache/commons/lang/StringUtils.html#line.170
I hope this would help
public static void main(String[] args) throws Exception
{ int count = 0;
String str = "ABthatCDthatBHthatIOthat";
StringBuffer sc = new StringBuffer(str);
while(str.contains("that")){
int aa = str.indexOf("that");
count++;
sc = sc.delete(aa, aa+3);
str = sc.toString();
}
System.out.println("count is:"+count);
}
Related
This question already has answers here:
Trim leading or trailing characters from a string?
(6 answers)
Closed 5 years ago.
I have the following string and I want to remove dynamic number of dot(.) at the end of the String.
"abc....."
Dot(.) can be more than one
Try this. It uses a regular expression to replace all dots at the end of your string with empty strings.
yourString.replaceAll("\\.+$", "");
Could do this to remove all .:
String a = "abc.....";
String new = a.replaceAll("[.]", "");
Remove just the trailing .'s:
String new = a.replaceAll("//.+$","");
Edit: Seeing the comment. To remove last n .'s
int dotsToRemove = 5; // whatever value n
String new = a.substring(0, s.length()-dotsToRemove);
how about using this function? seems to work faster than regex
public static String trimPoints(String txt)
{
char[] cs = txt.toCharArray();
int index =0;
for(int x =cs.length-1;x>=0;x--)
{
if(cs[x]=='.')
continue;
else
{
index = x+1;
break;
}
}
return txt.substring(0,index);
}
I'm new to java and I wrote this method to input a string word and output the word spelled backwards. The intent is to create a method and not use an already existing method such as the simple reverse. Please help point me in the direction of how to do this to reverse a word. I'm also trying to determine/count if there are palindromes. Please help! I've read other questions and I can't find anything specific enough to my case. I know that my code doesn't run, though I'm unsure how to fix it to get the correct output.
An example would be the word "backwards" to go to "sdrawkcab".
public static int reverseWord(String word) {
int palindromes = 0;
for (int i = word.length(); i >= 0; i--) {
System.out.print(i);
word.equalsIgnoreCase();
if (word.charAt(i)) == index(word.charAt(0 && 1))) {
palindromes++
System.out.println(palindromes)
}
return i;
}
}
There are multiple problems with your code.
1.The prototype of equalsIgnoreCase is
public boolean equalsIgnoreCase(String str);
So this method expect a String to be passed,but your not not passing anything here.To fix this,pass another string with whom you want to match your word like this..
word.equalsIgnoreCase("myAnotherString");
2.word.charAt(i);
Suppose word="qwerty",so indexing of each character will be like this
/* q w e r t y
0 1 2 3 4 5 */
So when you use i = word.length();i will 6 since word is of length 6.So
word.charAt(i) will search for character at index 6,but since there is not index 6,it will return an exception ArrayIndexOutOfBound.To fix this,start i from word.length()-1.
3.if (word.charAt(i));
This extra " ) ".Remove it.
Is Index() your own method?.If Yes,then check that also.
the below code prints the reverse of the input string and checks if it is a palindrome
public static void main(String[] args) {
String input = "dad";
char temp[] = input.toCharArray();//converting it to a array so that each character can be compared to the original string
char output[] = new char[temp.length];//taking another array of the same size as the input string
for (int i = temp.length - 1, j = 0; i >= 0; i--, j++) {//i variable for iterating through the input string and j variable for inserting data into output string.
System.out.print(temp[i]);//printing each variable of the input string in reverse order.
output[j] = temp[i];//inserting data into output string
}
System.out.println(String.valueOf(output));
if (String.valueOf(output).equalsIgnoreCase(input)) {//comparing the output string with the input string for palindrome check
System.out.println("palindrome");
}
}
Because your question about what is wrong with your code was already answered here is another way you could do it by using some concepts which are somewhat less low level than directly working with character arrays
public static boolean printWordAndCheckIfPalindrome(final String word) {
// Create a StringBuilder which helps when building a string
final StringBuilder reversedWordBuilder = new StringBuilder("");
// Get a stream of the character values of the word
word.chars()
// Add each character to the beginning of the reversed word,
// example for "backwards": "b", "ab", "cab", "kcab", ...
.forEach(characterOfString -> reversedWordBuilder.insert(0, (char) characterOfString));
// Generate a String out of the contents of the StringBuilder
final String reversedWord = reversedWordBuilder.toString();
// print the reversed word
System.out.println(reversedWord);
// if the reversed word equals the given word it is a palindrome
return word.equals(reversedWord);
}
hey guys i'm a newby to programming in java and i'm trying to figure out why i'm getting a string out of bounds on my secondary loop. I'm trying to create a spell checker & i'm not sure maybe i'm not doing this exactly right. I'm trying to check the word of a sentence and compare it to the other array of words and char each character until end of the length of toCheck, but doesn't work :\
Any help would be greatly appreciated!! thank you in advance
public static String suggestions (String toCheck, String [] words, Scanner kb)
{//start
int length=toCheck.length(),total=0, count = 0;
for(int x = 0;x<words.length;x++)
{
if(words[x].charAt(0)==(toCheck.charAt(0)))
for(int j = 0;j<length-1;j++)
{
if(toCheck.charAt(j)==words[x].charAt(j))
count++;
}
if(count>=((words[x].length())/2))
total++;}
System.out.println(total);
//System.out.printf("Not found - %s",toCheck);
//System.out.println("\nChoices 1 leave as it 2. Type replacement 3 Pick one " + Arrays.toString(suggest));
return toCheck;
}//end of suggestions
error message shown
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:686)
at CSCD210HW4.suggestions(CSCD210HW4.java:59)
at CSCD210HW4.main(CSCD210HW4.java:44)
Why don't you use compareTo instead of manual checking for different character. It will be more easy.
For example
count = Math.abs(words[x].compareTo(toCheck));
//It will return the difference of character in both string.
// Suppose words[x] = "abc" and toCheck = "adc" then count will be 1.
length is the size of the word to check.
you're trying to access words[x].charAt(j) which does not have to exist.
j is the length of the string toCheck
You can use the below code:
public class check {
public static boolean suggestions (String toCheck, ArrayList<String> words)
{
for(String word: words )
{
return (toCheck.toLowerCase().equalsIgnoreCase(word));
}
return false;
}
}
This question already has answers here:
How do I count the number of words in a string?
(8 answers)
Closed 9 years ago.
I want to count the words in my String in a int variable.
For example:
String text = "Hello my friends";
int number = 3;
or
String text = "I think it is better to go";
int number = 7;
How can I do that?
String text = "I think it is better to go";
int number = text.split(" ").length;
You can try following method.
int countWords (String input) {
String trim = in.trim();
if (trim.isEmpty()) return 0;
//separate string around spaces
return trim.split("\\s+").length;
}
Use text.split(" "); which will return you an Array of Strings. You can find the number of words by getting the size of that array.
Try to split the string with space string("\\s+") and count the size of array.
This question already has answers here:
Why does "split" on an empty string return a non-empty array?
(9 answers)
Behaviour of String.split() when input is empty
(2 answers)
Closed 9 years ago.
Here is my code:
serialNumbers = "";
String[] serialArray = serialNumbers.split(",");
int arrayLength = serialArray.length;
arrayLength is showing 1 even there have no value in serialArray. I was expecting that length should return 0 in this case.
From the doc:
If the expression does not match any part of the input then the
resulting array has just one element, namely this string.
Note that this doc is from the String.split(String, int) method, which is invoked from String.split(String)
Split always returns at least one element.
In the case that a separator is not found, the entire input is returned in a single-element array.
serialArray contains [""], which is 1 element
If you look at the implementation of String.class (refer snippet below). Here off shows the match count and this is the String currently being processed for split operation and you have ur string as serialNumbers = "";. Thats why it is returning one item in array.
// If no match was found, return this
if (off == 0)
return new String[]{this};
public class TestArgs {
public static void main(String[] args) {
String checkString = "";
System.out.println("" + splitString(checkString));
}
public static int splitString(String checkString) {
if (checkString.indexOf(",") != -1 || !"".equals(checkString)) {
System.out.println("hello " + checkString.split(",").length);
return checkString.split(",").length;
} else {
return 0;
}
}
}