Android - Editing my String so each word starts with a capital - java

I was wondering if someone could provide me some code or point me towards a tutrial which explain how I can convert my string so that each word begins with a capital.
I would also like to convert a different string in italics.
Basically, what my app is doing is getting data from several EditText boxes and then on a button click is being pushed onto the next page via intent and being concatenated into 1 paragraph. Therefore, I assume I need to edit my string on the intial page and make sure it is passed through in the same format.
Thanks in advance

You can use Apache StringUtils. The capitalize method will do the work.
For eg:
WordUtils.capitalize("i am FINE") = "I Am FINE"
or
WordUtils.capitalizeFully("i am FINE") = "I Am Fine"

Here is a simple function
public static String capEachWord(String source){
String result = "";
String[] splitString = source.split(" ");
for(String target : splitString){
result
+= Character.toUpperCase(target.charAt(0))
+ target.substring(1) + " ";
}
return result.trim();
}

The easiest way to do this is using simple Java built-in functions.
Try something like the following (method names may not be exactly right, doing it off the top of my head):
String label = Capitalize("this is my test string");
public String Capitalize(String testString)
{
String[] brokenString = testString.split(" ");
String newString = "";
for(String s : brokenString)
{
s.charAt(0) = s.charAt(0).toUpper();
newString += s + " ";
}
return newString;
}
Give this a try, let me know if it works for you.

Just add android:inputType="textCapWords" to your EditText in layout xml. This wll make all the words start with the Caps letter.

Strings are immutable in Java, and String.charAt returns a value, not a reference that you can set (like in C++). Pheonixblade9's will not compile. This does what Pheonixblade9 suggests, except it compiles.
public String capitalize(String testString) {
String[] brokenString = testString.split(" ");
String newString = "";
for (String s : brokenString) {
char[] chars = s.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
newString = newString + new String(chars) + " ";
}
//the trim removes trailing whitespace
return newString.trim();
}

String source = "hello good old world";
StringBuilder res = new StringBuilder();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print("Result: " + res.toString().trim());

Related

Why is the replace all method not working?

I am testing out the replaceAll() method of the String class and I am having problems with it.
I do not understand why my code does not replace whitespaces with an empty string.
Here's my code:
public static void main(String[] args) {
String str = " I like pie!#!#! It's one of my favorite things !1!!!1111";
str = str.toLowerCase();
str = str.replaceAll("\\p{Punct}", "");
str = str.replaceAll("[^a-zA-Z]", "");
str = str.replaceAll("\\s+", " ");
System.out.print(str);
}
Output:
ilikepieitsoneofmyfavoritethings
The problem is there are no whitespaces in your String after this:
str = str.replaceAll("[^a-zA-Z]", "");
which replaces all characters that are not letters, which includes whitespaces, with a blank (effectively deleting it).
Add whitespace to that character class so they don't get nuked:
str = str.replaceAll("[^a-zA-Z\\s]", "");
And this line may be deleted:
str = str.replaceAll("\\p{Punct}", "");
because it's redundant.
Final code:
String str = " I like pie!#!#! It's one of my favorite things !1!!!1111";
str = str.toLowerCase();
str = str.replaceAll("[^a-zA-Z\\s]", "");
str = str.replaceAll("\\s+", " ");
System.out.print(str);
Output:
i like pie its one of my favorite things
You may want to add str = str.trim(); to remove the leading space.

How to print the specific element in the splitted values in selenium java

String ActualValue = element.getAttribute("class");
String[] SplittedValue =ActualValue.split("");
Output: object_selected object_notselected
How to print the value object_selection in System.out.println(" ");
See, this
SplittedValue
is string array, and you can print array in multiple ways:
String actualValue = driver.findElement(By.xpath("//")).getAttribute("class");
String[] splittedValue = actualValue.split("");
System.out.println("Length of array:" + splittedValue.length);
if (splittedValue.length > 0) {
for(String str: splittedValue) {
System.out.println(str);
}
}
else {
System.out.println("Since lenght is zero, split was not properly, you may wanna check what you are passing in split method");
}
Not sure why you are using split like this split(""), probably you are looking for this split(" ")
Also if you are sure about the string elements, then you can directly print
them like this (Not recommended):
String actualValue = driver.findElement(By.xpath("//")).getAttribute("class");
String[] splittedValue = actualValue.split(" ");
System.out.println(splittedValue[0]);
System.out.println(splittedValue[1]);
You were close enough. Once you retrieve the value of classname i.e. object_selected object_notselected you can invoke split() with respect to the space character as the delimiter as follows:
String ActualValue = element.getAttribute("class");
// ActualValue = "object_selected object_notselected"
String[] SplittedValue = ActualValue.split(" ");
//printing object_selected
System.out.println(SplittedValue[0]);
//printing object_notselected
System.out.println(SplittedValue[1]);

Replace the words in String without using String replace

Is there any solution on how to replace words in string without using String replace?
As you all can see this is like hard coded it. Is there any method to make it dynamically? I heard that there is some library file able to make it dynamically but I am not very sure.
Any expert out there able to give me some solutions? Thank you so much and have a nice day.
for (int i = 0; i < results.size(); ++i) {
// To remove the unwanted words in the query
test = results.toString();
String testresults = test.replace("numFound=2,start=0,docs=[","");
testresults = testresults.replace("numFound=1,start=0,docs=[","");
testresults = testresults.replace("{","");
testresults = testresults.replace("SolrDocument","");
testresults = testresults.replace("numFound=4,start=0,docs=[","");
testresults = testresults.replace("SolrDocument{", "");
testresults = testresults.replace("content=[", "");
testresults = testresults.replace("id=", "");
testresults = testresults.replace("]}]}", "");
testresults = testresults.replace("]}", "");
testresults = testresults.replace("}", "");
In this case, you will need learn regular expression and a built-in String function String.replaceAll() to capture all possible unwanted words.
For example:
test.replaceAll("SolrDocument|id=|content=\\[", "");
Simply create and use a custom String.replace() method which happens to use the String.replace() method within it:
public static String customReplace(String inputString, String replaceWith, String... stringsToReplace) {
if (inputString.equals("")) { return replaceWith; }
if (stringsToReplace.length == 0) { return inputString; }
for (int i = 0; i < stringsToReplace.length; i++) {
inputString = inputString.replace(stringsToReplace[i], replaceWith);
}
return inputString;
}
In the example method above you can supply as many strings as you like to be replaced within the stringsToReplace parameter as long as they are delimited with a comma (,). They will all be replaced with what you supply for the replaceWith parameter.
Here is an example of how it can be used:
String test = "This is a string which contains numFound=2,start=0,docs=[ crap and it may also "
+ "have numFound=1,start=0,docs=[ junk in it along with open curly bracket { and "
+ "the SolrDocument word which might also have ]}]} other crap in there too.";
testResult = customReplace(strg, "", "numFound=2,start=0,docs=[ ", "numFound=1,start=0,docs=[ ",
+ "{ ", "SolrDocument ", "]}]} ");
System.out.println(testResult);
You can also pass a single String Array which contains all your unwanted strings within its elements and pass that array to the stringsToReplace parameter, for example:
String test = "This is a string which contains numFound=2,start=0,docs=[ crap and it may also "
+ "have numFound=1,start=0,docs=[ junk in it along with open curly bracket { and "
+ "the SolrDocument word which might also have ]}]} other crap in there too.";
String[] unwantedStrings = {"numFound=2,start=0,docs=[ ", "numFound=1,start=0,docs=[ ",
"{ ", "SolrDocument ", "]}]} "};
String testResult = customReplace(test, "", unwantedStrings);
System.out.println(testResult);

How to replace or convert the first occurrence of a dot from a string in java

Example:
Input
Str = P.O.Box
Output
Str= PO BOX
I can able to convert the string to uppercase and replace all dot(.) with a space.
public static void main(String args[]){
String s = "P.O.Box 1836";
String uppercase = s.toUpperCase();
System.out.println("uppercase "+uppercase);
String replace = uppercase.replace("."," ");
System.out.println("replace "+replace);
}
System.out.print(s.toUpperCase().replaceFirst("[.]", "").replaceAll("[.]"," "));
If you look the String API carefully, you would notice that there's a methods that goes by:-
replaceFirst(String regex, String replacement)
Hope it helps.
You have to use the replaceFirst method twice. First for replacing the . with <nothing>. Second for replacing the second . with a <space>.
String str = "P.O.Box";
str = str.replaceFirst("[.]", "");
System.out.println(str.replaceFirst("[.]", " "));
This one liner should do the job:
String s = "P.O.Box";
String replace = s.toUpperCase().replaceAll("\\.(?=[^.]*\\.)", "").replace('.', ' ');
//=> PO BOX
String resultValue = "";
String[] result = uppercase.split("[.]");
for (String value : result)
{
if (value.toCharArray().length > 1)
{
resultValue = resultValue + " " + value;
}
else
{
resultValue = resultValue + value;
}
}
Try this
System.out.println("P.O.Box".toUpperCase().replaceFirst("\\.","").replaceAll("\\."," "));
Out put
PO BOX
NOTE: \\ is needed here if you just use . only your out put will blank.
Live demo.
You should use replaceFirst method twice.
String replace = uppercase.replace("\\.", "").replaceFirst("\\.", "");
As you want to remove the first dot and replace the second one with a space, you need replace the whole P.O. section
Use
replace("P\\.O\\.", "PO ");

removal of repeated string

I have a string something like
JNDI Locations eis/FileAdapter,eis/FileAdapter used by composite
HelloWorld1.0.jar are not available in the
destination domain.
eis/FileAdapter,eis/FileAdapter is occuring twice.
I want it to be formatted as
JNDI Locations eis/FileAdapter used by composite
HelloWorld1.0.jar are not available in the
destination domain.
I tried below thing
String[ ] missingAdapters =((textMissingAdapterList.item(0)).getNodeValue().trim().split(","));
missingAdapters.get(0)
but i am missing second part any better way to handle this?
In your comment below the question you confirm, that the duplicates will alway be conencted via a comma. Using this information, this should work (for most cases):
String replaceCustomDuplicates(String str) {
if (str.indexOf(",") < 0) {
return str; // nothing to do
}
StringBuilder result = new StringBuilder(str.length());
for (String token : str.split(" ", -1)) {
if (token.indexOf(",") > 0) {
String[] parts = token.split(",");
if (parts.length == 2 && parts[0].equals(parts[1])) {
token = parts[0];
}
}
result.append(token + " ");
}
return result.delete(result.length() - 1, result.length()).toString();
}
a little demo with your example:
String str = "JNDI Locations eis/FileAdapter,eis/FileAdapter used by composite";
System.out.println(str);
str = replaceCustomDuplicates(str);
System.out.println(str);
Previous errors fixed
That should do it:
String[] missingAdapters = ((textMissingAdapterList.item(0)).getNodeValue().trim().split(","));
String result = missingAdapters[0] + " " + missingAdapters[1].split(" ", 2)[1];
assuming there is no space in this double string you want to leave out.

Categories