Excuse the brevity, currently on mobile.
I have a string array of values ABC, DEF, GHI that I would like to change to capitalized form: Abc, Def, Ghi
My code looks something like this:
import org.apache.commons.lang3.text.WordUtils;
....
final String[] split = stringToConvert.split(", ");
final StringBuilder sb = new StringBuilder();
for ( String s : split) {
//s = WordUtils.capitalizeFully(s.toLowerCase());
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(WordUtils.capitalizeFully(s.toLowerCase()));
}
return sb.toString();
The first value is always abc, but the second and following ones are correct, e.g. Def, Ghi. I don't know why the first value stays lowercase.
Any help would be appreciated!
Check your code again.
StringBuilder buf = new StringBuilder();
for (String str : new String[]{"ABC", "DEF", "GHI"})
buf.append(WordUtils.capitalizeFully(str.toLowerCase()));
System.out.println(buf);
Prints AbcDefGhi, as expected.
It could be simplier, if you use Stream:
String res = Stream.of("ABC", "DEF", "GHI")
.map(WordUtils::capitalizeFully)
.collect(Collectors.joining(", ")); // if you want to split words with comma
Your code should work.
May I however suggest using a stream instead?
String concatenatedString = Arrays.stream(array)
.map(WordUtils::capitalizeFully)
.collect(Collectors.joining());
Which, with appropriate static imports fits well on one line without losing readability:
String concatenatedString = stream(array).map(WordUtils::capitalizeFully).collect(joining());
Note that joining() uses a StringBuilder iternally, so you don't need to worry about performance here. Also, joining() allows you to choose which string you want to delimit the content of the stream with, in this case I chose an empty string, which would result in AbcDefGhi.
This should do :
String[] stringToSplit = {"ABC", "DEF", "GHI"};
StringBuilder sb = new StringBuilder();
for(String s: stringToSplit) {
sb.append(s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase());
}
Update: I'm tired...
The first character was actually a [ from the array instead of "a", thus the a was never capitalized
Thanks all, and sorry for wasting your time
Related
This program is to return the readable string for the given morse code.
class MorseCode{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String morseCode = scanner.nextLine();
System.out.println(getMorse(morseCode));
}
private static String getMorse(String morseCode){
StringBuilder res = new StringBuilder();
String characters = new String(morseCode);
String[] charactersArray = characters.split(" "); /*this method isn't
working for
splitting what
should I do*/
for(String charac : charactersArray)
res.append(get(charac)); /*this will return a string for the
corresponding string and it will
appended*/
return res.toString();
}
Can you people suggest a way to split up the string with multiple whitespaces. And can you give me some example for some other split operations.
Could you please share here the example of source string and the result?
Sharing this will help to understand the root cause.
By the way this code just works fine
String source = "a b c d";
String[] result = source.split(" ");
for (String s : result) {
System.out.println(s);
}
The code above prints out:
a
b
c
d
First, that method will only work if you have a specific number of spaces that you want to split by. You must also make sure that the argument on the split method is equal to the number of spaces you want to split by.
If, however, you want to split by any number of spaces, a smart way to do that would be trimming the string first (that removes all trailing whitespace), and then splitting by a single space:
charactersArray = characters.trim().split(" ");
Also, I don't understand the point of creating the characters string. Strings are immutable so there's nothing wrong with doing String characters = morseCode. Even then, I don't see the point of the new string. Why not just name your parameter characters and be done with it?
I am giving string input as "He is a very very good boy, isn't he?"
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
String[] split = s.split("[',',''','?','\\s','(',')',',',';']");
for(String s1:split){
if(s1.equalsIgnoreCase(""))
{
s1.trim();
}
System.out.println(s1);
}
Expected Result:
Actual Result:
Just put a + after your bracket for:
String[] split = s.split("[',',''','?','\\s','(',')',',',';']+");
Or simplify it to:
String[] split = s.split("[,'?\\s();]+");.
It will work how you expected since it will now match multiple characters in a row.
You will also no longer need to use trim() and just call:
for(String s1:split){
System.out.println(s1);
}
.trim() removes whitespace. I.e. " " becomes "". It is not able, however, to remove it from the list. String.split() doesn't know about your list.
The following will do what you want:
String[] split = s.split("<your regex>");
List<String> list = Arrays.asList(split);
list.stream() // convert to a stream for easy filtering
.filter(s -> s.trim().equals("")) // if s.trim().equals(""), remove it from the list/stream
.forEach(System.out::println); // print every remaining element
I am struggling with how to actually do this. Say I have this string
"This Str1ng i5 fun"
I want to replace the '1' with "One" and the 5 with "Five"
"This StrOneng iFive fun"
I have tried to loop thorough the string and manually replace them, but the count is off. I have also tried to use lists, arrays, stringbuilder, etc. but I cannot get it to work:
char[] stringAsCharArray = inputString.toCharArray();
ArrayList<Character> charArraylist = new ArrayList<Character>();
for(char character: stringAsCharArray) {
charArraylist.add(character);
}
int counter = startPosition;
while(counter < endPosition) {
char temp = charArraylist.get(counter);
String tempString = Character.toString(temp);
if(Character.isDigit(temp)){
char[] tempChars = digits.getDigitString(Integer.parseInt(tempString)).toCharArray(); //convert to number
charArraylist.remove(counter);
int addCounter = counter;
for(char character: tempChars) {
charArraylist.add(addCounter, character);
addCounter++;
}
counter += tempChars.length;
endPosition += tempChars.length;
}
counter++;
}
I feel like there has to be a simple way to replace a single character at a string with a substring, without having to do all this iterating. Am I wrong here?
String[][] arr = {{"1", "one"},
{"5", "five"}};
String str = "String5";
for(String[] a: arr) {
str = str.replace(a[0], a[1]);
}
System.out.println(str);
This would help you to replace multiple words with different text.
Alternatively you could use chained replace for doing this, eg :
str.replace(1, "One").replace(5, "five");
Check this much better approach : Java Replacing multiple different substring in a string at once (or in the most efficient way)
You can do
string = string.replace("1", "one");
Don't use replaceAll, because that replaces based on regular expression matches (so that you have to be careful about special characters in the pattern, not a problem here).
Despite the name, replace also replaces all occurrences.
Since Strings are immutable, be sure to assign the result value somewhere.
Try the below:
string = string.replace("1", "one");
string = string.replace("5", "five");
.replace replaces all occurences of the given string with the specified string, and is quite useful.
How can I avoid of StringIndexOutOfBoundsException in case when string starts with space (" ") or when there're several spaces in the string?
Actually I need to capitalize first letters of the words in the string.
My code looks like:
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
String[] array = s.split(" ");
for (String word : array) {
word = word.substring(0, 1).toUpperCase() + word.substring(1); //seems that here's no way to avoid extra spaces
System.out.print(word + " ");
}
}
Tests:
Input: "test test test"
Output: "Test Test Test"
Input: " test test test"
Output:
StringIndexOutOfBoundsException
Expected: " Test Test test"
I'm a Java newbie and any help is very appreciated. Thanks!
split will try to break string in each place where delimiter is found. So if you split on space and space if placed at start of the string like
" foo".split(" ")
you will get as result array which will contain two elements: empty string "" and "foo"
["", "foo"]
Now when you call "".substring(0,1) or "".substring(1) you are using index 1 which doesn't belong to that string.
So simply before you do any String modification based on indexes check if it is safe by testing string length. So check if word you are trying to modify has length grater than 0, or use something more descriptive like if(!word.isEmpty()).
A slight modification to Capitalize first word of a sentence in a string with multiple sentences.
public static void main( String[] args ) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
int pos = 0;
boolean capitalize = true;
StringBuilder sb = new StringBuilder(s);
while (pos < sb.length()) {
if (sb.charAt(pos) == ' ') {
capitalize = true;
} else if (capitalize && !Character.isWhitespace(sb.charAt(pos))) {
sb.setCharAt(pos, Character.toUpperCase(sb.charAt(pos)));
capitalize = false;
}
pos++;
}
System.out.println(sb.toString());
}
I would avoid using split and go with StringBuilder instead.
Instead of splitting the string, try to simply iterate over all characters within the original string, replacing all characters by its uppercase in case it's the first character of this string or if its predecessor is a space.
Use a regex in your split split all whitespaces
String[] words = s.split("\\s+");
Easier would be to use existing libraries: WordUtils.capitalize(str) (from apache commons-lang).
To fix your current code however, a possible solution would be to use a regex for words (\\w) and a combination of StringBuffer/StringBuilder setCharAt and Character.toUpperCase:
public static void main(String[] args) {
String test = "test test test";
StringBuffer sb = new StringBuffer(test);
Pattern p = Pattern.compile("\\s+\\w"); // Matches 1 or more spaces followed by 1 word
Matcher m = p.matcher(sb);
// Since the sentence doesn't always start with a space, we have to replace the first word manually
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
while (m.find()) {
sb.setCharAt(m.end() - 1, Character.toUpperCase(sb.charAt(m.end() - 1)));
}
System.out.println(sb.toString());
}
Output:
Test Test Test
Capitalize whole words in String using native Java streams
It is really elegant solution and doesnt require 3rd party libraries
String s = "HELLO, capitalized worlD! i am here! ";
CharSequence wordDelimeter = " ";
String res = Arrays.asList(s.split(wordDelimeter.toString())).stream()
.filter(st -> !st.isEmpty())
.map(st -> st.toLowerCase())
.map(st -> st.substring(0, 1).toUpperCase().concat(st.substring(1)))
.collect(Collectors.joining(wordDelimeter.toString()));
System.out.println(s);
System.out.println(res);
The output is
HELLO, capitalized worlD! i am here!
Hello, Capitalized World! I Am Here!
How to convert an ArrayList<Character> to a String in Java?
The List.toString method returns it as [a,b,c] string - I want to get rid of the brackets (etcetera) and store it as abc.
You can iterate through the list and create the string.
String getStringRepresentation(ArrayList<Character> list)
{
StringBuilder builder = new StringBuilder(list.size());
for(Character ch: list)
{
builder.append(ch);
}
return builder.toString();
}
Setting the capacity of the StringBuilder to the list size is an important optimization. If you don't do this, some of the append calls may trigger an internal resize of the builder.
As an aside, toString() returns a human-readable format of the ArrayList's contents. It is not worth the time to filter out the unnecessary characters from it. It's implementation could change tomorrow, and you will have to rewrite your filtering code.
Here a possible one-line solution using Java8 streams.
a) List of Character objects to String :
String str = chars.stream()
.map(e->e.toString())
.reduce((acc, e) -> acc + e)
.get();
b) array of chars (char[] chars)
String str = Stream.of(chars)
.map(e->new String(e))
.reduce((acc, e) -> acc + e)
.get();
UPDATE (following comment below):
a) List of Character objects to String :
String str = chars.stream()
.map(e->e.toString())
.collect(Collectors.joining());
b) array of chars (char[] chars)
String str = Stream.of(chars)
.map(e->new String(e))
.collect(Collectors.joining());
Note that the map(e->e.toString()) step in the above solutions will create a temporary string for each character in the list. The strings immediately become garbage. So, if the performance of the conversion is a relevant concern, you should consider using the StringBuilder approach instead.
How about this, Building the list
List<Character> charsList = new ArrayList<Character>();
charsList.add('h');
charsList.add('e');
charsList.add('l');
charsList.add('l');
charsList.add('o');
Actual code to get String from List of Character:
String word= new String();
for(char c:charsList){
word= word+ c;
}
System.out.println(word);
Still learning if there is a misake point out.
You can do it using toString() and RegExp without any loops and streams:
List<Character> list = Arrays.asList('a', 'b', 'c');
String s = list.toString().replaceAll("[,\\s\\[\\]]", "");
Assuming you have a following list:
final ArrayList<Character> charsList = new ArrayList<Character>();
charsList.add('h');
charsList.add('e');
charsList.add('l');
charsList.add('l');
charsList.add('o');
This will yield hello (I am using org.apache.commons.lang.ArrayUtils helper class):
final Character[] charactersArray =
charsList.toArray(new Character[charsList.size()]);
final char[] charsArray = ArrayUtils.toPrimitive(charactersArray);
System.out.println(String.valueOf(charsArray));
Using join of a Joiner class:
// create character list and initialize
List<Character> arr = Arrays.asList('a', 'b', 'c');
String str = Joiner.on("").join(arr);
System.out.println(str);
Use toString then remove , and spaces
import com.google.common.base.Joiner;
....
<Character> arr = Arrays.asList('h', 'e', 'l', 'l', 'o');
// remove [] and spaces
String str = arr.toString()
.substring(1, 3 * str.size() - 1) //3 bcs of commas ,
.replaceAll(", ", "");
System.out.println(str);
Or by using streams:
import java.util.stream.Collectors;
...
// using collect and joining() method
String str = arr.stream().map(String::valueOf).collect(Collectors.joining());
Easiest is to loop through.
List<String> strings = new ArrayList<String>();
// populate strings
StringBuilder builder = new StringBuilder();
for(String string : strings) {
builder.append(string).append(',');
}
if(builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
System.out.println(builder);
Many solutions available. You can iterate over the chars and append to a StringBuilder, then when finished appending, call .toString on the StringBuilder.
Or use something like commons-lang StringUtils.join from the apache commons-lang project.
a tiny complement to #waggledans 's answer
a) List of Character objects to String :
String str = chars.stream().map(e->e.toString()).collect(Collectors.joining());
which e->e.toString() can be replaced by Object::toString
String str = chars.stream().map(Object::toString).collect(Collectors.joining());
I consider this an easy and smart way
// given list containing the chars
List<Character> arr = Arrays.asList('a', 'b', 'c');
//convert list to string
String output = arr.toString().replaceAll("[ ,]","")
.substring(1, tmpArr.length()-1);
Explanation:
// convert to string.
String str = arr.toString(); // result is "[a ,b ,c]"
// get rid of the start and the end char i.e '[' & ']'
str = str.substring(1, tmpArr.length()-1); //result is "a ,b ,c"
// replace <space> and ','
str = str.replaceAll(" ,","") "ABC"
I would say :
public String arayListToString(ArrayList arrayList){
StringBuffer b = new StringBuffer();
for(String s : arrayList){
b.append(s);
b.append(",");
}
return b.toString();
}
private void countChar() throws IOException {
HashMap hashMap = new HashMap();
List list = new ArrayList();
list = "aammit".chars().mapToObj(r -> (char) r).collect(Collectors.toList());
list.stream().forEach(e -> {
hashMap.computeIfPresent(e, (K, V) -> (int) V + 1);
hashMap.computeIfAbsent(e, (V) -> 1);
});
System.out.println(hashMap);
}