Program to Sort the String - string

I want to sort the String s = "eBaDcAfg153E" Such that the sorted string contains All lowercase first and then uppercase letters and then numbers.
The output should be like s = "acefgABDE135"
Can anyone help me with that?
Thanks

Welcome to stackoverflow!
Read how to ask good question, First try to solve, and if fail then first search over Google. and if you don't find answer, then you may ask.
This solution may work for you (just for test).. Still you can improve it a lot..
Use StringBuilder for string modification.
public static void main (String[] args) throws java.lang.Exception
{
String inputString = "eBaDcAfg153E";
String lowerCase = "";
String upperCase = "";
String numberCase = "";
for (int i = 0; i < inputString.length(); i++) {
char c = inputString.charAt(i);
if(Character.isUpperCase(c)) {
upperCase += c;
}else if (Character.isLowerCase(c)) {
lowerCase += c;
}else if(Character.isDigit(c)) {
numberCase += c;
}
}
char upperArray[] = upperCase.toCharArray();
char lowerArray[] = lowerCase.toCharArray();
char numArray[] = numberCase.toCharArray();
Arrays.sort(upperArray);
Arrays.sort(lowerArray);
Arrays.sort(numArray);
System.out.println(new String(lowerArray)+""+new String(upperArray)+""+new String(numArray));
}

Related

XSSFCell in Apache POI encodes certain character sequences as unicode character

XSSFCell seems to encode certain character sequences as unicode characters. How can I prevent this? Do I need to apply some kind of character escaping?
e.g.
cell.setCellValue("LUS_BO_WP_x24B8_AI"); // The cell value now is „LUS_BO_WPⒸAI"
In Unicode Ⓒ is U+24B8
I've already tried setting an ANSI font and setting the cell type to string.
This character conversion is done in XSSFRichTextString.utfDecode()
I have now written a function that basicaly does the same thing in reverse.
private static final Pattern utfPtrn = Pattern.compile("_(x[0-9A-F]{4}_)");
private static final String UNICODE_CHARACTER_LOW_LINE = "_x005F_";
public static String escape(final String value) {
if(value == null) return null;
StringBuffer buf = new StringBuffer();
Matcher m = utfPtrn.matcher(value);
int idx = 0;
while(m.find()) {
int pos = m.start();
if( pos > idx) {
buf.append(value.substring(idx, pos));
}
buf.append(UNICODE_CHARACTER_LOW_LINE + m.group(1));
idx = m.end();
}
buf.append(value.substring(idx));
return buf.toString();
}
Based on what #matthias-gerth suggested with little adaptations:
Create your own XSSFRichTextString class
Adapt XSSFRichTextString.setString like this: st.setT(s); >> st.setT(escape(s));
Adapt the constructor of XSSFRichTextString like this: st.setT(str); >> st.setT(escape(str));
Add this stuff in XSSFRichTextString (which is very near to Matthias suggestion):
private static final Pattern PATTERN = Pattern.compile("_x[a-fA-F0-9]{4}");
private static final String UNICODE_CHARACTER_LOW_LINE = "_x005F";
private String escape(String str) {
if (str!=null) {
Matcher m = PATTERN.matcher(str);
if (m.find()) {
StringBuffer buf = new StringBuffer();
int idx = 0;
do {
int pos = m.start();
if( pos > idx) {
buf.append(str.substring(idx, pos));
}
buf.append(UNICODE_CHARACTER_LOW_LINE + m.group(0));
idx = m.end();
} while (m.find());
buf.append(str.substring(idx));
return buf.toString();
}
}
return str;
}

Reversing the letters in words in a String

I have coded the following solution, and it works, except for when there is punctuation. I was wondering if there are O(1) space complexity and O(length of string) time complexity solutions, without using reverse() method, or anything similar that makes this task too easy. Any answer that can also handle punctuation correctly would be great.
Example:
Given string: "I love chocolate"
Return string should be: "I evol etalocohc"
For clarity, when I say handle punctuation correctly, I mean punctuation should not move around.
// reverse the letters of every word in a sentence (string), and return the result
public static String reverse(String x)
{
String[] str = x.split(" ");
StringBuilder rev = new StringBuilder("");
for (int i = 0; i < str.length; i++)
{
for (int s = str[i].length()-1; s >= 0; s--)
{
rev.append(str[i].charAt(s));
}
rev.append(" ");
}
return rev.toString();
}
Here is my output for some tests of mine:
public static void main(String[] args)
{
System.out.println(reverse("I love chocolate"));//this passes
System.out.println(reverse("Geeks for Geeks"));//this passes
System.out.println(reverse("You, are awesome"));//not handling puncutation mark correctly, gives me ",uoY era emosewa", instead of "uoY, era emosewa"
System.out.println(reverse("Geeks! for Geeks."));//not handling puncutation marks correctly, gives me "!skeeG rof .skeeG", instead of "skeeG! rof skeeG."
}
This would probably work with the punctuation:
public static String reverse(String x)
{
String[] str = x.split("\\W"); //Split on non-word characters.
StringBuilder rev = new StringBuilder("");
int currentPosition = 0;
for (int i = 0; i < str.length; i++)
{
for (int s = str[i].length()-1; s >= 0; s--)
{
rev.append(str[i].charAt(s));
currentPosition++;
}
while (currentPosition < x.length() && Character.toString(x.charAt(currentPosition)).matches("\\W"))
rev.append(x.charAt(currentPosition++)); //Add the actual character there.
}
return rev.toString();
}
Haven't coded in Java in a while now so I know it's probably not best practices here.
Complexity is O(n) (space and time).
If you start off with a string builder you might be able to lower space complexity by using in-place character swaps instead of appending, but you'd need to preemptively find where all the non-word characters are.
Here is an implementation which uses in-place reversing of words requiring only O(1) storage. In addition, the reversing algorithm itself is O(N) with the length of the string.
The basic algorithm is to walk down the string until hitting a space. Then, the swap() method is called to reverse that particular word in place. It only needs at any moment one extra character.
This approach may not be as performant as the accepted answer due to its heavy use of StringBuilder manipulations. But this might something to consider in an environment like an Android application where space is very precious.
public static void swap(StringBuilder input, int start, int end) {
for (int i=0; i <= (end - start) / 2; ++i) {
char ch = input.charAt(start + i);
input.setCharAt(start + i, input.charAt(end - i));
input.setCharAt(end - i, ch);
}
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("I love chocolate");
int start = 0;
int end = 0;
while (true) {
while (end <= sb.length() - 1 && sb.charAt(end) != ' ') {
++end;
}
swap(sb, start, end - 1);
start = end + 1;
end = start;
if (end > sb.length() - 1) {
break;
}
}
System.out.println(sb);
}
Demo here:
Rextester
A compact solution is
public static String reverse(String x) {
Matcher m = Pattern.compile("\\w+").matcher(x);
if(!m.find()) return x;
StringBuffer target = new StringBuffer(x.length());
do m.appendReplacement(target, new StringBuilder(m.group()).reverse().toString());
while(m.find());
return m.appendTail(target).toString();
}
The appendReplacement loop + appendTail on a Matcher is the manual equivalent of String.replaceAll(regex), intended to support exactly such cases where the replacement is more complex than a simple string with placeholders, like reversing the found words.
Unfortunately, we have to use the outdated StringBuffer here, as the API is older than StringBuilder. Java 9 is going to change that.
A potentially more efficient alternative is
public static String reverse(String x) {
Matcher m = Pattern.compile("\\w+").matcher(x);
if(!m.find()) return x;
StringBuilder target = new StringBuilder(x.length());
int last=0;
do {
int s = m.start(), e = m.end();
target.append(x, last, s).append(new StringBuilder(e-s).append(x, s, e).reverse());
last = e;
}
while(m.find());
return target.append(x, last, x.length()).toString();
}
This uses StringBuilder throughout the operation and usese the feature to append partial character sequences, not creating intermediate strings for the match and replacement. It also elides the search for placeholders in the replacement, which appendReplacement does internally.
I just have made changes on your code, not additional methods or loops, just some variables and if conditions.
/* Soner - The methods reverse a string with preserving punctiations */
public static String reverse(String x) {
String[] str = x.split(" ");
boolean flag = false;
int lastCharPosition;
StringBuilder rev = new StringBuilder("");
for (int i = 0; i < str.length; i++) {
flag = false;
lastCharPosition = str[i].length()-1;
if (str[i].charAt(lastCharPosition) == '.' || str[i].charAt(lastCharPosition) == '!'
|| str[i].charAt(lastCharPosition) == ',') { // you can add new punctiations
flag = true;
lastCharPosition = str[i].length()-2;
}
for (int s = lastCharPosition; s >= 0; s--) {
rev.append(str[i].charAt(s));
}
if (flag) rev.append(str[i].charAt(lastCharPosition + 1));
rev.append(" ");
}
return rev.toString();
}

Special characters - String - Binary - Java

I tried to convert a String to binary and back. It works very well, but if I have a special character, like €, in the String it gives me a questionmark back. How can I solve this?
This is my Code for converting a String to binary:
// stringToBinary
public static String stringToBinary(String message) {
byte[] bytes = message.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
for (int i = 0; i < 8; i++) {
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
return binary.toString();
}
And I use this Code for doing it the other way around with each "block":
// binaryToChar
public static char binaryToChar(String block) {
int ascii = Integer.parseInt(block, 2);
return (char) ascii;
}
Thank you for your help and sorry for my bad English ;)
EDIT: I found € in this list: >>Klick<<
So it is right, that € is displayed as 10000000 in binary, but it isn't shown as this after reconverting to a String/char.
Wow, I can answer my own question :O
I edited my Code a Little bit and tried some Things and now this works:
// stringToBinary
public static String stringToBinary(String message) {
StringBuilder binary = new StringBuilder();
for (char c : message.toCharArray()) {
int i = (int) c;
binary.append(Integer.toBinaryString(i));
binary.append(' ');
}
return binary.toString();
}
Thanks to everyone who thought about my question :)

Cut a string and paste it in a List?

I have a string like that:
string exampleStr = "0123456789 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Now I want to write a function like that:
private void StringCut(string str, int cut) {
//... Cut string and put it in a string list
}
You can give the string to a function with an int value.
E.g.
StringCut(exampleStr, 5);
Now the function should cut the string in 5 pieces and put the string pieces in a List.
How can I do that?
I tried to split the string with:
exampleStr.Substring(... , ... ));
But it's a lot of work. Is there a fast way to do that?
I don't tried exampleStr.Split, because the text and the length of the string is always different.
I made it. If someone needs it.
C# code:
private int maxStrLength = 30;
private List<string> StringCut(string getStr, int cut) {
List<string> strToList = new List<string>();
int getStringLength = getStr.Length;
if (getStringLength > maxStrLength) {
// GREATER
float tmpDiv = (float)getStringLength/(float)maxStrLength;
int roundTmpDiv = (int)System.Math.Ceiling(tmpDiv);
for (int i = 0; i < roundTmpDiv; i++) {
string tmpStr = "";
if (i != roundTmpDiv-1) {
tmpStr = getStr.Substring(i*maxStrLength, maxStrLength);
} else {
int rest = getStr.Length-((roundTmpDiv-1)*maxStrLength);
tmpStr = getStr.Substring(i*maxStrLength, rest);
}
strToList.Add(tmpStr);
}
} else {
// LOWER
strToList.Add(getStr);
}
return strToList;
}
void Start() {
string testString = "0123456789 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
List<string> tmpStr = StringCut (testString, 2);
foreach (string tmpString in tmpStr){
print (tmpString);
}
}
Please post your code here, if you have a better solution.

String replace in Java ME double space

How can I replace "a b" by "a b" in Java ME?
The replace() method doesn't accept Strings, but only characters. And since a double space contains two characters, I think I have a small problem.
What do you think of this one? I tried one myself.
private String replace(String needle, String replacement, String haystack) {
String result = "";
int index = haystack.indexOf(needle);
if(index==0) {
result = replacement+haystack.substring(needle.length());
return replace(needle, replacement, result);
}else if(index>0) {
result = haystack.substring(0,index)+ replacement +haystack.substring(index+needle.length());
return replace(needle, replacement, result);
}else {
return haystack;
}
}
Here's one function you might use:
public static String replace(String _text, String _searchStr, String _replacementStr) {
// String buffer to store str
StringBuffer sb = new StringBuffer();
// Search for search
int searchStringPos = _text.indexOf(_searchStr);
int startPos = 0;
int searchStringLength = _searchStr.length();
// Iterate to add string
while (searchStringPos != -1) {
sb.append(_text.substring(startPos, searchStringPos)).append(_replacementStr);
startPos = searchStringPos + searchStringLength;
searchStringPos = _text.indexOf(_searchStr, startPos);
}
// Create string
sb.append(_text.substring(startPos,_text.length()));
return sb.toString();
}

Resources