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)
Related
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);
}
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);
}
This question already has answers here:
how to get data between quotes in java?
(6 answers)
Closed 6 years ago.
I have a string of names. I am looking to split it based on names between double quotes. I used the following code to split the names.
String []splitterString=str.split("\"");
for (String s : splitterString) {
System.out.println(s);
}
I get the output as:
[
Hossain, Ziaul
,
Sathiaseelan, Arjuna
,
Secchi, Raffaello
,
Fairhurst, Gorry
]
I need to store just the names from these. I am not sure how to do that.
This is the string:
["Hossain, Ziaul","Sathiaseelan, Arjuna","Secchi, Raffaello","Fairhurst, Gorry"]
Thanks for the help!!!
I think following solution may help you out :-
String str = "[\"Hossain, Ziaul\",\"Sathiaseelan, Arjuna\",\"Secchi, Raffaello\",\"Fairhurst, Gorry\"]";
String [] str1 = str.split("\\[\"|\",\"|\"\\]");
for (int iCount = 0; iCount < str1.length; iCount++)
{
System.out.println(str1[iCount]);
}
I try to write equals override function. I think I have written right but the problem is that parsing the expression. I have an array type of ArrayList<String> it takes inputs from keyboard than evaluate the result. I could compare with another ArrayList<String> variable but how can I compare the ArrayList<String> to String. For example,
String expr = "(5 + 3) * 12 / 3";
ArrayList<String> userInput = new ArrayList<>();
userInput.add("(");
userInput.add("5");
userInput.add(" ");
userInput.add("+");
userInput.add(" ");
userInput.add("3");
.
.
userInput.add("3");
userInput.add(")");
then convert userInput to String then compare using equals
As you see it is too long when a test is wanted to apply.
I have used to split but It splits combined numbers as well. like 12 to 1 and 2
public fooConstructor(String str)
{
// ArrayList<String> holdAllInputs; it is private member in class
holdAllInputs = new ArrayList<>();
String arr[] = str.split("");
for (String s : arr) {
holdAllInputs.add(s);
}
}
As you expect it doesn't give the right result. How can it be fixed? Or can someone help to writing regular expression to parse it properly as wanted?
As output I get:
(,5, ,+, ,3,), ,*, ,1,2, ,/, ,3
instead of
(,5, ,+, ,3,), ,*, ,12, ,/, ,3
The Regular Expression which helps you here is
"(?<=[-+*/()])|(?=[-+*/()])"
and of course, you need to avoid unwanted spaces.
Here we go,
String expr = "(5 + 3) * 12 / 3";
.
. // Your inputs
.
String arr[] = expr.replaceAll("\\s+", "").split("(?<=[-+*/()])|(?=[-+*/()])");
for (String s : arr)
{
System.out.println("Element : " + s);
}
Please see my expiriment : http://rextester.com/YOEQ4863
Hope it helps.
Instead of splitting the input into tokens for which you don't have a regex, it would be good to move ahead with joining the strings in the List like:
StringBuilder sb = new StringBuilder();
for (String s : userInput)
{
sb.append(s);
}
then use sb.toString() later for comparison. I would not advice String concatenation using + operator details here.
Another approach to this would be to use one of the the StringUtils.join methods in Apache Commons Lang.
import org.apache.commons.lang3.StringUtils;
String result = StringUtils.join(list, "");
If you are fortunate enough to be using Java 8, then it's even easier...just use String.join
String result = String.join("", list);
More details on this approach available here
this makes all the inputs into one string which can then be can be compared against the expression to see if it is equal
String x = "";
for(int i = 0; i < holdAllInputs.length; i++){
x = x + holdAllInputs.get(i);
}
if(expr == x){
//do something equal
}else{
//do something if not equal
}
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.