Reformatting a Java String

I have a line that looks like this:

CALDARI_STARSHIP_ENGINEERING 

and I need to edit it to look like

 Caldari Starship Engineering 

Unfortunately, it is three in the morning, and I can’t let life understand me. I always had problems replacing the material in the lines, so any help would be awesome and help me figure out how to do this in the future.

+4
source share
5 answers

Something like this is simple enough:

  String text = "CALDARI_STARSHIP_ENGINEERING"; text = text.replace("_", " "); StringBuilder out = new StringBuilder(); for (String s : text.split("\\b")) { if (!s.isEmpty()) { out.append(s.substring(0, 1) + s.substring(1).toLowerCase()); } } System.out.println("[" + out.toString() + "]"); // prints "[Caldari Starship Engineering]" 

It is split at the anchor border of the anchor.

see also


Matcher solution loop

If you don't mind using StringBuffer , you can also use the Matcher.appendReplacement/Tail loop as follows:

  String text = "CALDARI_STARSHIP_ENGINEERING"; text = text.replace("_", " "); Matcher m = Pattern.compile("(?<=\\b\\w)\\w+").matcher(text); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, m.group().toLowerCase()); } m.appendTail(sb); System.out.println("[" + sb.toString() + "]"); // prints "[Caldari Starship Engineering]" 

The regular expression uses the statement to match the β€œtail” of the part of the word, the part that needs to be reduced. He looks behind (?<=...) to see that there is a word boundary \b followed by the character \w . Any remaining \w+ must then be matched so that they can be reduced.

Related Questions

+9
source

You can try the following:

 String originalString = "CALDARI_STARSHIP_ENGINEERING"; String newString = WordUtils.capitalize(originalString.replace('_', ' ').toLowerCase()); 

WordUtils are part of the Commons Lang libraries ( http://commons.apache.org/lang/ )

+4
source

Using reg-exps:

 String s = "CALDARI_STARSHIP_ENGINEERING"; StringBuilder camel = new StringBuilder(); Matcher m = Pattern.compile("([^_])([^_]*)").matcher(s); while (m.find()) camel.append(m.group(1)).append(m.group(2).toLowerCase()); 
+1
source

Unconfirmed, but here's how I did it a while ago:

 s = "CALDARI_STARSHIP_ENGINEERING"; StringBuilder b = new StringBuilder(); boolean upper = true; for(char c : s.toCharArray()) { if( upper ) { b.append(c); upper = false; } else if( c = '_' ) { b.append(" "); upper = true; } else { b.append(Character.toLowerCase(c)); } } s = b.toString(); 

Please note that EVE license agreements can generate external tools that will help you in your career. And this may be a trigger for you to learn Python, because most EVE is written in Python :).

0
source

Quick and dirty way:

Lowercase all

  line.toLowerCase(); 

Divide into words:

  String[] words = line.split("_"); 

Then loop the words, capital letters:

  words[i].substring(0, 1).toUpperCase() 
0
source

Source: https://habr.com/ru/post/1309900/


All Articles