remove the last part of a string in java - java

String Y="part1 part2 part3",X="part1";
boolean foundMatch = false;
while(!foundMatch) {
foundMatch = Y.equals(X);
if(foundMatch) {
break;
}
else {
Y = useSplitToRemoveLastPart(Y);
if(Y.equals("")) {
break;
}
}
//implementation of useSplitToRemoveLastPart()
private static String useSplitToRemoveLastPart(String y) {
//What goes here .. It should chop the last part of the string..
return null;
}
Can anyone help ...

If you want part3 to be removed and provided that all the words are separated by space
String str ="part1 part2 part3";
String result = str.substring(0,str.lastIndexOf(" "));

If you really want to use split:
private static String useSplitToRemoveLastPart(String str) {
String[] arr = str.split(" ");
String result = "";
if (arr.length > 0) {
result = str.substring(0, str.lastIndexOf(" " + arr[arr.length-1]));
}
return result;
}

Your whole code can be optimized to:
boolean foundmatch = y.startsWith(x);
y = foundmatch? x : "";

public String removeLastSubstring(String target, String toRemove){
int idx = target.lastIndexOf(toRemove);
target = target.substring(0, idx) + target.substring(idx + toRemove.length());
return target;
}
You only need to pass it your target and the LAST substring you want to remove, example:
String s = "123 #abc# 456";
s = removeLastSubstring(s, "#abc#");

If you want to do it using split, then you can do:
String s[] = Y.split(" ");
String n = "";
for (int i = 0; i < s.length - 1; i++)
n+= s[i];
return n;

By the way, If the method you need to build is called useSplitToRemoveLastPart(String t), then I'd suggest you to use split to remove last part.
Take a look here.

Related

Find the longest word in a String

Following is my code:
String LongestWord(String a)
{
int lw=0;
int use;
String lon="";
while (!(a.isEmpty()))
{
a=a.trim();
use=a.indexOf(" ");
if (use<0)
{
break;
}
String cut=a.substring(0,use);
if(cut.length()>lw)
{
lon=cut;
}
lw=lon.length();
a=a.replace(cut," ");
}
return lon;
}
The problem is that when I input a string like,
"a boy is playing in the park"
it returns the longest word as "ying" because when it replaces 'cut' with " " for the first time, it removes all the 'a'-s too, such that it becomes
" boy is pl ying in the p rk" after the first iteration of the loop
Please figure out what's wrong?
Thanks in advance!
You have already known the problem: the program does unwanted replacement.
Therefore, stop doing replacement.
In this program, the word examined is directly cut instead of using the harmful replacement.
String LongestWord(String a)
{
int lw=0;
int use;
String lon="";
while (!(a.isEmpty()))
{
a=a.trim();
use=a.indexOf(" ");
if (use<0)
{
break;
}
String cut=a.substring(0,use);
if(cut.length()>lw)
{
lon=cut;
}
lw=lon.length();
a=a.substring(use+1); // cut the word instead of doing harmful replacement
}
return lon;
}
You can use the split function to get an array of strings.
Than cycle that array to find the longest string and return it.
String LongestWord(String a) {
String[] parts = a.split(" ");
String longest = null;
for (String part : parts) {
if (longest == null || longest.length() < part.length()) {
longest = part;
}
}
return longest;
}
I would use arrays:
String[] parts = a.split(" ");
Then you can loop over parts, for each element (is a string) you can check length:
parts[i].length()
and find longest one.
I would use a Scanner to do this
String s = "the boy is playing in the parl";
int length = 0;
String word = "";
Scanner scan = new Scanner(s);
while(scan.hasNext()){
String temp = scan.next();
int tempLength = temp.length();
if(tempLength > length){
length = tempLength;
word = temp;
}
}
}
You check the length of each word, if it's longer then all the previous you store that word into the String "word"
Another way uses Streams.
Optional<String> max = Arrays.stream("a boy is playing in the park"
.split(" "))
.max((a, b) -> a.length() - b.length());
System.out.println("max = " + max);
if you are looking for not trivial Solution ,you can solve it without using split or map but with only one loop
static String longestWorld(String pharagragh) {
int maxLength = 0;
String word=null,longestWorld = null;
int startIndexOfWord = 0, endIndexOfWord;
int wordLength = 0;
for (int i = 0; i < pharagragh.length(); i++) {
if (pharagragh.charAt(i) == ' ') {
endIndexOfWord = i;
wordLength = endIndexOfWord - startIndexOfWord;
word = pharagragh.substring(startIndexOfWord, endIndexOfWord);
startIndexOfWord = endIndexOfWord + 1;
if (wordLength > maxLength) {
maxLength = wordLength;
longestWorld = word;
}
}
}
return longestWorld;
}
now lets test it
System.out.println(longestWorld("Hello Stack Overflow Welcome to Challenge World"));// output is Challenge
Try :
package testlongestword;
/**
*
* #author XOR
*/
public class TestLongestWord{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(LongestWord("a boy is playing in the park"));
}
public static String LongestWord(String str){
String[] words = str.split(" ");
int index = 0;
for(int i = 0; i < words.length; ++i){
final String current = words[i];
if(current.length() > words[index].length()){
index = i;
}
}
return words[index];
}
}

How to split string at every nth occurrence of character in Java

I would like to split a string at every 4th occurrence of a comma ,.
How to do this? Below is an example:
String str = "1,,,,,2,3,,1,,3,,";
Expected output:
array[0]: 1,,,,
array[1]: ,2,3,,
array[2]: 1,,3,,
I tried using Google Guava like this:
Iterable<String> splitdata = Splitter.fixedLength(4).split(str);
output: [1,,,, ,,2,, 3,,1, ,,3,, ,]
I also tried this:
String [] splitdata = str.split("(?<=\\G.{" + 4 + "})");
output: [1,,,, ,,2,, 3,,1, ,,3,, ,]
Yet this is is not the output I want. I just want to split the string at every 4th occurrence of a comma.
Thanks.
Take two int variable. One is to count the no of ','. If ',' occurs then the count will move. And if the count is go to 4 then reset it to 0. The other int value will indicate that from where the string will be cut off. it will start from 0 and after the first string will be detected the the end point (char position in string) will be the first point of the next. Use the this start point and current end point (i+1 because after the occurrence happen the i value will be incremented). Finally add the string in the array list. This is a sample code. Hope this will help you. Sorry for my bad English.
String str = "1,,,,,2,3,,1,,3,,";
int k = 0;
int startPoint = 0;
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ',')
{
k++;
if (k == 4)
{
String ab = str.substring(startPoint, i+1);
System.out.println(ab);
arrayList.add(ab);
startPoint = i+1;
k = 0;
}
}
}
Here's a more flexible function, using an idea from this answer:
static List<String> splitAtNthOccurrence(String input, int n, String delimiter) {
List<String> pieces = new ArrayList<>();
// *? is the reluctant quantifier
String regex = Strings.repeat(".*?" + delimiter, n);
Matcher matcher = Pattern.compile(regex).matcher(input);
int lastEndOfMatch = -1;
while (matcher.find()) {
pieces.add(matcher.group());
lastEndOfMatch = matcher.end();
}
if (lastEndOfMatch != -1) {
pieces.add(input.substring(lastEndOfMatch));
}
return pieces;
}
This is how you call it using your example:
String input = "1,,,,,2,3,,1,,3,,";
List<String> pieces = splitAtNthOccurrence(input, 4, ",");
pieces.forEach(System.out::println);
// Output:
// 1,,,,
// ,2,3,,
// 1,,3,,
I use Strings.repeat from Guava.
try this also, if you want result in array
String str = "1,,,,,2,3,,1,,3,,";
System.out.println(str);
char c[] = str.toCharArray();
int ptnCnt = 0;
for (char d : c) {
if(d==',')
ptnCnt++;
}
String result[] = new String[ptnCnt/4];
int i=-1;
int beginIndex = 0;
int cnt=0,loopcount=0;
for (char ele : c) {
loopcount++;
if(ele==',')
cnt++;
if(cnt==4){
cnt=0;
result[++i]=str.substring(beginIndex,loopcount);
beginIndex=loopcount;
}
}
for (String string : result) {
System.out.println(string);
}
This work pefectly and tested in Java 8
public String[] split(String input,int at){
String[] out = new String[2];
String p = String.format("((?:[^/]*/){%s}[^/]*)/(.*)",at);
Pattern pat = Pattern.compile(p);
Matcher matcher = pat.matcher(input);
if (matcher.matches()) {
out[0] = matcher.group(1);// left
out[1] = matcher.group(2);// right
}
return out;
}
//Ex: D:/folder1/folder2/folder3/file1.txt
//if at = 2, group(1) = D:/folder1/folder2 and group(2) = folder3/file1.txt
The accepted solution above by Saqib Rezwan does not add the leftover string to the list, if it divides the string after every 4th comma and the length of the string is 9 then it will leave the 9th character, and return the wrong list.
A complete solution would be :
private static ArrayList<String> splitStringAtNthOccurrence(String str, int n) {
int k = 0;
int startPoint = 0;
ArrayList<String> list = new ArrayList();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',') {
k++;
if (k == n) {
String ab = str.substring(startPoint, i + 1);
list.add(ab);
startPoint = i + 1;
k = 0;
}
}
// if there is no comma left and there are still some character in the string
// add them to list
else if (!str.substring(i).contains(",")) {
list.add(str.substring(startPoint));
break;
}
}
return list;
}
}

Deleting the set substring from string

I need to delete the set substring from string in Java. How I can to do it?
example:
string st1="The end of the text";
string st2="end of the ";
result:
st1="The text".
You can do this:
String newString = st1.replace(st2, "");
// String newString2 = st1.replaceAll(st2, ""); Alternative
// String newString3 = st1.replaceFirst(st2, ""); Alternative 2
However, your question smell homework so you should add that tag on future questions if this is true.
Java String documentation
Does the following do what you are looking for?
str1 = st1.replace(st2,"");
If you want to use substring(), you can do it like this:
public static String getCustomString(String s1, String s2)
{
if(s1.length() >= s2.length())
{
if(s1.contains(s2))
return s1.substring(0, s1.indexOf(s2)) + s1.substring(s1.indexOf(s2) + s2.length());
}
else
{
if(s2.contains(s1))
return s2.substring(0, s2.indexOf(s1)) + s2.substring(s2.indexOf(s1) + s1.length());
}
return "";
}
If homework (with minimal usage of Java API calls:
public void subString(String st1, String st2) {
int s2len = st2.length();
int s1len = st1.length();
int i = 0;
int count = 0;
while(i <= st1.length() && i+st2.length() <= st1.length()) {
if (st1.substring(i, i+st2.length()).equalsIgnoreCase(st2)) {
st1 = (i > 0? st1.substring(0, i) : "") + st1.substring(i+st2.length());
i=0;
}
else {
i++;
}
}
System.out.println(st1);
}
Otherwise:
st1.replace(st2, "");

How to flip two words in a string, Java

So say I have a string called x that = "Hello world". I want to somehow make it so that it will flip those two words and instead display "world Hello". I am not very good with loops or arrays and obviously am a beginner. Could I accomplish this somehow by splitting my string? If so, how? If not, how could I do this? Help would be appreciated, thanks!
1) split string into String array on space.
String myArray[] = x.split(" ");
2) Create new string with words in reverse order from array.
String newString = myArray[1] + " " + myArray[0];
Bonus points for using a StringBuilder instead of concatenation.
String abc = "Hello world";
String cba = abc.replace( "Hello world", "world Hello" );
abc = "This is a longer string. Hello world. My String";
cba = abc.replace( "Hello world", "world Hello" );
If you want, you can explode your string as well:
String[] pieces = abc.split(" ");
for( int i=0; i<pieces.length-1; ++i )
if( pieces[i]=="Hello" && pieces[i+1]=="world" ) swap(pieces[i], pieces[i+1]);
There are many other ways you can do it too. Be careful for capitalization. You can use .toUpperCase() in your if statements and then make your matching conditionals uppercase, but leave the results with their original capitalization, etc.
Here's the solution:
import java.util.*;
public class ReverseWords {
public String reverseWords(String phrase) {
List<String> wordList = Arrays.asList(phrase.split("[ ]"));
Collections.reverse(wordList);
StringBuilder sbReverseString = new StringBuilder();
for(String word: wordList) {
sbReverseString.append(word + " ");
}
return sbReverseString.substring(0, sbReverseString.length() - 1);
}
}
The above solution was coded by me, for Google Code Jam and is also blogged here: Reverse Words - GCJ 2010
Just use this method, call it and pass the string that you want to split out
static String reverseWords(String str) {
// Specifying the pattern to be searched
Pattern pattern = Pattern.compile("\\s");
// splitting String str with a pattern
// (i.e )splitting the string whenever their
// is whitespace and store in temp array.
String[] temp = pattern.split(str);
String result = "";
// Iterate over the temp array and store
// the string in reverse order.
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1) {
result = temp[i] + result;
} else {
result = " " + temp[i] + result;
}
}
return result;
}
Depending on your exact requirements, you may want to split on other forms of whitespace (tabs, multiple spaces, etc.):
static Pattern p = Pattern.compile("(\\S+)(\\s+)(\\S+)");
public String flipWords(String in)
{
Matcher m = p.matcher(in);
if (m.matches()) {
// reverse the groups we found
return m.group(3) + m.group(2) + m.group(1);
} else {
return in;
}
}
If you want to get more complex see the docs for Pattern http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
Try something as follows:
String input = "how is this";
List<String> words = Arrays.asList(input.split(" "));
Collections.reverse(words);
String result = "";
for(String word : words) {
if(!result.isEmpty()) {
result += " ";
}
result += word;
}
System.out.println(result);
Output:
this is how
Too much?
private static final Pattern WORD = Pattern.compile("^(\\p{L}+)");
private static final Pattern NUMBER = Pattern.compile("^(\\p{N}+)");
private static final Pattern SPACE = Pattern.compile("^(\\p{Z}+)");
public static String reverseWords(final String text) {
final StringBuilder sb = new StringBuilder(text.length());
final Matcher wordMatcher = WORD.matcher(text);
final Matcher numberMatcher = NUMBER.matcher(text);
final Matcher spaceMatcher = SPACE.matcher(text);
int offset = 0;
while (offset < text.length()) {
wordMatcher.region(offset, text.length());
numberMatcher.region(offset, text.length());
spaceMatcher.region(offset, text.length());
if (wordMatcher.find()) {
final String word = wordMatcher.group();
sb.insert(0, reverseCamelCase(word));
offset = wordMatcher.end();
} else if (numberMatcher.find()) {
sb.insert(0, numberMatcher.group());
offset = numberMatcher.end();
} else if (spaceMatcher.find()) {
sb.insert(0, spaceMatcher.group(0));
offset = spaceMatcher.end();
} else {
sb.insert(0, text.charAt(offset++));
}
}
return sb.toString();
}
private static final Pattern CASE_REVERSAL = Pattern
.compile("(\\p{Lu})(\\p{Ll}*)(\\p{Ll})$");
private static String reverseCamelCase(final String word) {
final StringBuilder sb = new StringBuilder(word.length());
final Matcher caseReversalMatcher = CASE_REVERSAL.matcher(word);
int wordEndOffset = word.length();
while (wordEndOffset > 0 && caseReversalMatcher.find()) {
sb.insert(0, caseReversalMatcher.group(3).toUpperCase());
sb.insert(0, caseReversalMatcher.group(2));
sb.insert(0, caseReversalMatcher.group(1).toLowerCase());
wordEndOffset = caseReversalMatcher.start();
caseReversalMatcher.region(0, wordEndOffset);
}
sb.insert(0, word.substring(0, wordEndOffset));
return sb.toString();
}

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

The title pretty much says it all. What's the simplest/most elegant way that I can convert, in Java, a string from the format "THIS_IS_AN_EXAMPLE_STRING" to the format "ThisIsAnExampleString"? I figure there must be at least one way to do it using String.replaceAll() and a regex.
My initial thoughts are: prepend the string with an underscore (_), convert the whole string to lower case, and then use replaceAll to convert every character preceded by an underscore with its uppercase version.
Another option is using Google Guava's com.google.common.base.CaseFormat
George Hawkins left a comment with this example of usage:
CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING");
Take a look at WordUtils in the Apache Commons lang library:
Specifically, the capitalizeFully(String str, char[] delimiters) method should do the job:
String blah = "LORD_OF_THE_RINGS";
assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, '_').replaceAll("_", ""));
Green bar!
static String toCamelCase(String s){
String[] parts = s.split("_");
String camelCaseString = "";
for (String part : parts){
camelCaseString = camelCaseString + toProperCase(part);
}
return camelCaseString;
}
static String toProperCase(String s) {
return s.substring(0, 1).toUpperCase() +
s.substring(1).toLowerCase();
}
Note: You need to add argument validation.
With Apache Commons Lang3 lib is it very easy.
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
public String getName(String text) {
return StringUtils.remove(WordUtils.capitalizeFully(text, '_'), "_");
}
Example:
getName("SOME_CONSTANT");
Gives:
"SomeConstant"
Here is a code snippet which might help:
String input = "ABC_DEF";
StringBuilder sb = new StringBuilder();
for( String oneString : input.toLowerCase().split("_") )
{
sb.append( oneString.substring(0,1).toUpperCase() );
sb.append( oneString.substring(1) );
}
// sb now holds your desired String
Java 1.8 example using Streams
String text = "THIS_IS_SOME_TEXT";
String bactrianCamel = Stream.of(text.split("[^a-zA-Z0-9]"))
.map(v -> v.substring(0, 1).toUpperCase() + v.substring(1).toLowerCase())
.collect(Collectors.joining());
String dromedaryCamel = bactrianCamel.toLowerCase().substring(0, 1) + bactrianCamel.substring(1);
System.out.printf("%s is now %s%n", text, dromedaryCamel);
THIS_IS_SOME_TEXT is now thisIsSomeText
public static void main(String[] args) {
String start = "THIS_IS_A_TEST";
StringBuffer sb = new StringBuffer();
for (String s : start.split("_")) {
sb.append(Character.toUpperCase(s.charAt(0)));
if (s.length() > 1) {
sb.append(s.substring(1, s.length()).toLowerCase());
}
}
System.out.println(sb);
}
The Apache Commons project does now have the CaseUtils class, which has a toCamelCase method that does exactly as OP asked:
CaseUtils.toCamelCase("THIS_IS_AN_EXAMPLE_STRING", true, '_');
Sorry for mine five cents, I think in java too many words))
I just wondering. Why is the regexp engine in java not so familiar with lambdas as in JS((
Anyway. With java 8+ construction appears in my mind:
Arrays.stream("THIS_IS_AN_EXAMPLE_STRING".split("_"))
.collect(StringBuilder::new,
(result, w) -> result
.append(w.substring(0, 1).toUpperCase())
.append(w.substring(1).toLowerCase()),
StringBuilder::append)
.toString())
If you care about memory consumption, the below code care about it:
"THIS_IS_AN_EXAMPLE_STRING".chars().collect(StringBuilder::new,
(result, c) -> {
// Detect place for deal with
if (result.length() > 0 && result.charAt(result.length() - 1) == '_') {
result.setCharAt(result.length() - 1,
Character.toUpperCase((char) c));
} else if (result.length() > 0) {
result.append(Character.toLowerCase((char) c));
} else {
result.append(Character.toUpperCase((char) c));
}
}, StringBuilder::append).toString()
You can use org.modeshape.common.text.Inflector.
Specifically:
String camelCase(String lowerCaseAndUnderscoredWord,
boolean uppercaseFirstLetter, char... delimiterChars)
By default, this method converts strings to UpperCamelCase.
Maven artifact is: org.modeshape:modeshape-common:2.3.0.Final
on JBoss repository: https://repository.jboss.org/nexus/content/repositories/releases
Here's the JAR file: https://repository.jboss.org/nexus/content/repositories/releases/org/modeshape/modeshape-common/2.3.0.Final/modeshape-common-2.3.0.Final.jar
Not sure, but I think I can use less memory and get dependable performance by doing it char-by-char. I was doing something similar, but in loops in background threads, so I am trying this for now. I've had some experience with String.split being more expensive then expected. And I am working on Android and expect GC hiccups to be more of an issue then cpu use.
public static String toCamelCase(String value) {
StringBuilder sb = new StringBuilder();
final char delimChar = '_';
boolean lower = false;
for (int charInd = 0; charInd < value.length(); ++charInd) {
final char valueChar = value.charAt(charInd);
if (valueChar == delimChar) {
lower = false;
} else if (lower) {
sb.append(Character.toLowerCase(valueChar));
} else {
sb.append(Character.toUpperCase(valueChar));
lower = true;
}
}
return sb.toString();
}
A hint that String.split is expensive is that its input is a regex (not a char like String.indexOf) and it returns an array (instead of say an iterator because the loop only uses one things at a time). Plus cases like "AB_AB_AB_AB_AB_AB..." break the efficiency of any bulk copy, and for long strings use an order of magnitude more memory then the input string.
Whereas looping through chars has no canonical case. So to me the overhead of an unneeded regex and array seems generally less preferable (then giving up possible bulk copy efficiency). Interested to hear opinions / corrections, thanks.
public String withChars(String inputa) {
String input = inputa.toLowerCase();
StringBuilder sb = new StringBuilder();
final char delim = '_';
char value;
boolean capitalize = false;
for (int i=0; i<input.length(); ++i) {
value = input.charAt(i);
if (value == delim) {
capitalize = true;
}
else if (capitalize) {
sb.append(Character.toUpperCase(value));
capitalize = false;
}
else {
sb.append(value);
}
}
return sb.toString();
}
public String withRegex(String inputa) {
String input = inputa.toLowerCase();
String[] parts = input.split("_");
StringBuilder sb = new StringBuilder();
sb.append(parts[0]);
for (int i=1; i<parts.length; ++i) {
sb.append(parts[i].substring(0,1).toUpperCase());
sb.append(parts[i].substring(1));
}
return sb.toString();
}
Times: in milli seconds.
Iterations = 1000
WithChars: start = 1379685214671 end = 1379685214683 diff = 12
WithRegex: start = 1379685214683 end = 1379685214712 diff = 29
Iterations = 1000
WithChars: start = 1379685217033 end = 1379685217045 diff = 12
WithRegex: start = 1379685217045 end = 1379685217077 diff = 32
Iterations = 1000
WithChars: start = 1379685218643 end = 1379685218654 diff = 11
WithRegex: start = 1379685218655 end = 1379685218684 diff = 29
Iterations = 1000000
WithChars: start = 1379685232767 end = 1379685232968 diff = 201
WithRegex: start = 1379685232968 end = 1379685233649 diff = 681
Iterations = 1000000
WithChars: start = 1379685237220 end = 1379685237419 diff = 199
WithRegex: start = 1379685237419 end = 1379685238088 diff = 669
Iterations = 1000000
WithChars: start = 1379685239690 end = 1379685239889 diff = 199
WithRegex: start = 1379685239890 end = 1379685240585 diff = 695
Iterations = 1000000000
WithChars: start = 1379685267523 end = 1379685397604 diff = 130081
WithRegex: start = 1379685397605 end = 1379685850582 diff = 452977
You can Try this also :
public static String convertToNameCase(String s)
{
if (s != null)
{
StringBuilder b = new StringBuilder();
String[] split = s.split(" ");
for (String srt : split)
{
if (srt.length() > 0)
{
b.append(srt.substring(0, 1).toUpperCase()).append(srt.substring(1).toLowerCase()).append(" ");
}
}
return b.toString().trim();
}
return s;
}
protected String toCamelCase(String input) {
if (input == null) {
return null;
}
if (input.length() == 0) {
return "";
}
// lowercase the first character
String camelCaseStr = input.substring(0, 1).toLowerCase();
if (input.length() > 1) {
boolean isStartOfWord = false;
for (int i = 1; i < input.length(); i++) {
char currChar = input.charAt(i);
if (currChar == '_') {
// new word. ignore underscore
isStartOfWord = true;
} else if (Character.isUpperCase(currChar)) {
// capital letter. if start of word, keep it
if (isStartOfWord) {
camelCaseStr += currChar;
} else {
camelCaseStr += Character.toLowerCase(currChar);
}
isStartOfWord = false;
} else {
camelCaseStr += currChar;
isStartOfWord = false;
}
}
}
return camelCaseStr;
}
public String CamelCase(String str)
{
String CamelCase="";
String parts[] = str.split("_");
for(String part:parts)
{
String as=part.toLowerCase();
int a=as.length();
CamelCase = CamelCase + as.substring(0, 1).toUpperCase()+ as.substring(1,a);
}
return CamelCase;
}
This is the Simplest Program to convert into CamelCase.
hope it Will Help You..
public static String toCamelCase(String value) {
value = value.replace("_", " ");
String[] parts = value.split(" ");
int i = 0;
String camelCaseString = "";
for (String part : parts) {
if (part != null && !part.isEmpty()) {
if (i == 0) {
camelCaseString = part.toLowerCase();
} else if (i > 0 && part.length() > 1) {
String oldFirstChar = part.substring(0, 1);
camelCaseString = camelCaseString + part.replaceFirst(oldFirstChar, oldFirstChar.toUpperCase());
} else {
camelCaseString = camelCaseString + part + " ";
}
i++;
}
}
return camelCaseString;
}
public static void main(String[] args) {
String string = "HI_tHiS_is_SomE Statement";
System.out.println(toCamelCase(string));
}
It will convert Enum Constant into Camel Case. It would be helpful for anyone who is looking for such funtionality.
public enum TRANSLATE_LANGUAGES {
ARABIC("ar"), BULGARIAN("bg"), CATALAN("ca"), CHINESE_SIMPLIFIED("zh-CN"), CHINESE_TRADITIONAL("zh-TW"), CZECH("cs"), DANISH("da"), DUTCH("nl"), ENGLISH("en"), ESTONIAN("et"), FINNISH("fi"), FRENCH(
"fr"), GERMAN("de"), GREEK("el"), HAITIAN_CREOLE("ht"), HEBREW("he"), HINDI("hi"), HMONG_DAW("mww"), HUNGARIAN("hu"), INDONESIAN("id"), ITALIAN("it"), JAPANESE("ja"), KOREAN("ko"), LATVIAN(
"lv"), LITHUANIAN("lt"), MALAY("ms"), NORWEGIAN("no"), PERSIAN("fa"), POLISH("pl"), PORTUGUESE("pt"), ROMANIAN("ro"), RUSSIAN("ru"), SLOVAK("sk"), SLOVENIAN("sl"), SPANISH("es"), SWEDISH(
"sv"), THAI("th"), TURKISH("tr"), UKRAINIAN("uk"), URDU("ur"), VIETNAMESE("vi");
private String code;
TRANSLATE_LANGUAGES(String language) {
this.code = language;
}
public String langCode() {
return this.code;
}
public String toCamelCase(TRANSLATE_LANGUAGES lang) {
String toString = lang.toString();
if (toString.contains("_")) {
String st = toUpperLowerCase(toString.split("_"));
}
return "";
}
private String toUpperLowerCase(String[] tempString) {
StringBuilder builder = new StringBuilder();
for (String temp : tempString) {
String char1 = temp.substring(0, 1);
String restString = temp.substring(1, temp.length()).toLowerCase();
builder.append(char1).append(restString).append(" ");
}
return builder.toString();
}
}
One more solution to this may be as follows.
public static String toCamelCase(String str, String... separators) {
String separatorsRegex = "\\".concat(org.apache.commons.lang3.StringUtils.join(separators, "|\\"));
List splits = Arrays.asList(str.toLowerCase().split(separatorsRegex));
String capitalizedString = (String)splits.stream().map(WordUtils::capitalize).reduce("", String::concat);
return capitalizedString.substring(0, 1).toLowerCase() + capitalizedString.substring(1);
}
public static final String UPPER_CAMEL = "initUp";
public static final String LOWER_CAMEL = "initLow";
public String toCamel(String src, String separator, String format) {
StringBuilder builder = new StringBuilder(src.toLowerCase());
int len = builder.length();
for (int idx = builder.indexOf(separator); idx > 0 && idx < len; idx = builder.indexOf(separator, idx)) {
builder = builder.replace(idx, idx + 2, (String.valueOf(builder.charAt(idx + 1)).toUpperCase()));
}
switch (format) {
case LOWER_CAMEL:
builder.setCharAt(0, Character.toLowerCase(builder.charAt(0)));
break;
default:
builder.setCharAt(0, Character.toUpperCase(builder.charAt(0)));
break;
}
return builder.toString();
}
Invocation as
toCamel("THIS_IS_AN_EXAMPLE_STRING", "_", UPPER_CAMEL)
Execution Time: 14 ms
A simple snnipet:
public static String camelCase(String in) {
if (in == null || in.length() < 1) { return ""; } //validate in
String out = "";
for (String part : in.toLowerCase().split("_")) {
if (part.length() < 1) { //validate length
continue;
}
out += part.substring(0, 1).toUpperCase();
if (part.length() > 1) { //validate length
out += part.substring(1);
}
}
return out;
}
protected String toCamelCase(CaseFormat caseFormat, String... words){
if (words.length == 0){
throw new IllegalArgumentException("Word list is empty!");
}
String firstWord = words[0];
String [] restOfWords = Arrays.copyOfRange(words, 1, words.length);
StringBuffer buffer = new StringBuffer();
buffer.append(firstWord);
Arrays.asList(restOfWords).stream().forEach(w->buffer.append("_"+ w.toUpperCase()));
return CaseFormat.UPPER_UNDERSCORE.to(caseFormat, buffer.toString());
}
Java 8 for multiple strings:
import com.google.common.base.CaseFormat;
String camelStrings = "YOUR_UPPER, YOUR_TURN, ALT_TAB";
List<String> camelList = Arrays.asList(camelStrings.split(","));
camelList.stream().forEach(i -> System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, i) + ", "));

Categories

Resources