Easier way to convert string of ascii numbers to string of letters? - java

so I have the string "116,101,115,116,49,50,51,52" and I want to convert it from ASCII decimals to ASCII letters. This is the code I'm using to do that:
String charInts = "116,101,115,116,49,50,51,52";
String[] tokenizedCharInts = charInts.split(",");
String phrase = "";
for (int i = 0; i < tokenizedCharInts.length; i++) {
int digit = Integer.parseInt(tokenizedCharInts[i]);
phrase += (char) digit;
}
System.out.println(phrase);
It works so I'm fairly happy with it, but I'm wondering if anyone knows a more elegant way of doing this instead, perhaps without using that for loop (having to convert each split string to an int, then a char, then append it, for every small sub-string, makes me feel like their must be a cleaner solution).

Using StringBuilder and other for maybe? :
String charInts = "116,101,115,116,49,50,51,52";
String[] tokenizedCharInts = charInts.split(",");
StringBuilder phrase = new StringBuilder();
for (String a : tokenizedCharInts) {
phrase.append((char)Integer
.parseInt(a));
}
System.out.println(phrase);

You can use an enhanced for loop, since you don't need the array element index.
You should use a StringBuilder to accumulate the string instead of String phrase, to avoid repeated string construction.

You can use Scanner and StringBuilder combo : (no need to split the String and loop though it.)
String charInts = "116,101,115,116,49,50,51,52";
Scanner scanner=new Scanner(charInts);
scanner.useDelimiter(",");
StringBuilder sb=new StringBuilder();
while (scanner.hasNextInt()) {
sb.append((char)scanner.nextInt());
}
scanner.close();
System.out.println(sb.toString());

Java-8 solution:
String charInts = "116,101,115,116,49,50,51,52";
String phrase = Arrays.stream(charInts.split(",")).mapToInt(Integer::parseInt)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
System.out.println(phrase);

IF this fits your use-case:
char[] charInts = new char[] { 116,101,115,116,49,50,51,52 };
String s = new String(charInts);

Yes, Java provides an elegant, single-line solution using Streams API.
String charInts = "116,101,115,116,49,50,51,52";
StringBuilder sb = new StringBuilder();
Arrays.stream(charInts.split(","))
.map(Integer::parseInt)
.map(Character::toChars)
.forEach(sb::append);
System.out.println(sb.toString());

Related

Java capitalizing first letter of every word in string array

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

Java: Replace a specific character with a substring in a string at index

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.

Use a regular expression but keep what was replaced?

I need a regular expression to remove certain characters but preserve what was removed into a new string. I'm hoping to avoid using two separate expressions.
Example,
Lets say I want to remove all numbers from a string but preserve them and place them in a different string.
"a1b23c" would become "abc" AND a new string for "123"
Thanks for any help!
You can do what you describe with a find / replace loop using Matcher.appendReplacement() and Matcher.appendTail(). For your example:
Matcher matcher = Pattern.compile("\\d+").matcher("a1b23c");
StringBuffer nonDigits = new StringBuffer();
StringBuffer digits = new StringBuffer();
while (matcher.find()) {
digits.append(matcher.group());
matcher.appendReplacement(nonDigits, "");
}
matcher.appendTail(nonDigits);
System.out.println(nonDigits);
System.out.println(digits);
Output:
abc
123
You do have to use StringBuffer instead of StringBuilder for this approach, because that's what Matcher supports.
If you are doing simple things like removing digits, it would be easier to use a pair of StringBuilders:
StringBuilder digits = new StringBuilder();
StringBuilder nonDigits = new StringBuilder();
for (int i = 0; i < str.length(); ++i) {
char ch = str.charAt(i);
if (Character.isDigit(ch) {
digits.append(ch);
} else {
nonDigits.append(ch);
}
}
System.out.println(nonDigits);
System.out.println(digits);

How to replace each indice of a substring

String s = "Elephant";
String srep = (s.replaceAll(s.substring(4,6), "_" ));
System.out.println(srep);
So my code outputs Elep_nt But I want it to replace each individual indice of that substring with an underscore so that it would output Elep__nt
is there anyway to do this in a single line? would I have to use a loop?
The problem with yours is that you are matching "ha" at once, thus it gets replaced by only one char. (Notice also if you had "Elephantha" the last "ha" would be replaced as well.)
You could use a lookbehind to determine each single character to be replaced. So to "replace chars from position 4 to 5" you could use:
String s = "Elephant";
String srep = s.replaceAll("(?<=^.{4,5}).", "_");
System.out.println(srep);
Output:
Elep__nt
You can use a StringBuilder:
StringBuilder result = new StringBuilder(s.length());
result.append(s.substring(0, 4));
for (int i = 4; i < 6; i++)
result.append('_');
result.append(s.substring(6));
String srep = result.toString();
System.out.println(srep);
Elep__nt
Since you have asked for oneliner here is another possible way.
String srep = s.substring(0,4)+s.substring(4,6).replaceAll(".", "_")+s.substring(6);
Or using StringBuilder
String srep = new StringBuilder(s).replace(4, 6, s.substring(4,6).replaceAll(".", "_")).toString();
Output
Elep__nt
But note that internally regex replaceAll uses loop anyways
int difference = 6-4;
StringBuilder sb = new StringBuilder();
for(int count=0; count<difference; count++){
sb.append("_");
}
String s = "Elephant";
String srep = (s.replaceAll(s.substring(4,6), sbsb.toString() ));

Converting ArrayList of Characters to a String?

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);
}

Categories