Count Words from a string containing \n [duplicate] - java

This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 6 years ago.
I have below mentioned string
String str = "\nArticle\n\nArticle\nArticle";
I want total number of count. How can i get this?
As the string contain \n so always it gives 1 instead of 3

To get you started, I will show you a simple example:
String str = "\nArticle\n\nArticle\nArticle";
// Split the String by \n
String[] words = str.split("\n");
// Keep the count of words
int wordCount = 0;
for(String word : words){
// Only count non-empty Strings
if(!word.isEmpty()) {
wordCount++;
}
}
// Check, answer is 3
System.out.println(wordCount);

Related

Split a String using split function to count number of "that" [duplicate]

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);
}

Remove n number of dot(.) from String in Java [duplicate]

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);
}

count occurences of successive characters of a string [duplicate]

This question already has answers here:
Java compressing Strings
(21 answers)
Closed 7 years ago.
I have a String and I need to count occurances of successive characters of the string.
String s1="aabbcccaaa";
It should print output as
a2b2c3a3
String s1="aabbcccaaa";
char c[]=s1.toCharArray();
StringBuffer sb=new StringBuffer();
LinkedHashMap<Character,Integer> map=new LinkedHashMap<Character,Integer>();
for(int i=0;i<c.length;i++)
{
Character c1=c[i];
Integer frequency=map.get(c1);
map.put(c1, (frequency==null)?1:frequency+1);
if(map.size()>1 && c[i]!=c[i-1])
{
sb.append(c[i-1]+""+map.get(c[i-1]));
map.remove(c[i-1]);
}
}
sb.append(map);
System.out.println(sb);
I am not sure how i can achieve counts if same elements occur again.
Hint #1: Test the current character against the previous one.
Hint #2: Ask yourself, why do you need to use a Map?

how to print first Characters from multiple string in java? [duplicate]

This question already has answers here:
Get string character by index
(13 answers)
Closed 8 years ago.
i want to print first character from multiple word , this word coming from api , like
DisplayName: arwa othman .
i want to print the letter (a) and (o).
can anyone to help me please ??
Try this
public String getFirstWords(String original){
String firstWord= "";
String[] split = original.split(" ");
for(String value : split){
firstWord+= value.substring(0,1);
}
return firstWord;
}
And use this as
String Result = getFirstWords("arwa othman");
Edit
Using Regex
String name = "arwa othman";
String firstWord= "";
for(String s : name.split("\\s+")){
firstWord += s.charAt(0);
}
String Result = firstWord;
You can use the the Apache Commons Langs library and use the initials() method , you can get more information from here http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#initials(java.lang.String)
I am quoting a sample code snippet that might be useful :
WordUtils.initials(null) = null
WordUtils.initials("") = ""
WordUtils.initials("Ben John Lee") = "BJL"
WordUtils.initials("Ben J.Lee") = "BJ"
This may work for you:
String[] splitArray = displayName.split("\\s+");
char[] initials = new char[splitArray.length];
for (int i = 0; i < splitArray.length; i++) {
initials[i] = splitArray[i].charAt(0);
}
This will give you a char array. If you want a String array use String.valueOf(char)

How to count words in String [duplicate]

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.

Categories