String replace in Java ME double space - string

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

Related

Program to Sort the 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));
}

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

Anagram-compare two strings

I am trying to write a function that determines if two strings are anagrams of each other. I give the function two strings that are equal except for case, and it fails, even though I ignore case in my comparison.
Test case:
hello
Hello
for these input my output is NOT an anagram, but it is an anagram
SOURCE CODE:
static boolean isAnagram(String a, String b) {
char[] a1 = a.toCharArray();
char[] b1 = b.toCharArray();
Arrays.sort(a1);
Arrays.sort(b1);
String x = new String(a1);
String y = new String(b1);
int i=0,flag=0;
while(i < a1.length)
{
if(x.equalsIgnoreCase(y)){
i++;
}
else
return false;
}
return true;
}
You do not need the while loop;
static boolean isAnagram(String a, String b) {
char []a1= a.toLowerCase().toCharArray();
char []b1= b.toLowerCase().toCharArray();
Arrays.sort(a1);
Arrays.sort(b1);
String x= new String(a1), y = new String(b1);
return x.equals(y);
}
Check out the below methods for Anagram Check:
/**
* Java program - String Anagram Example.
* This program checks if two Strings are anagrams or not
*/
public class AnagramCheck {
/*
* One way to find if two Strings are anagram in Java. This method
* assumes both arguments are not null and in lowercase.
*
* #return true, if both String are anagram
*/
public static boolean isAnagram(String word, String anagram){
if(word.length() != anagram.length()){
return false;
}
char[] chars = word.toCharArray();
for(char c : chars){
int index = anagram.indexOf(c);
if(index != -1){
anagram = anagram.substring(0,index) + anagram.substring(index +1, anagram.length());
}else{
return false;
}
}
return anagram.isEmpty();
}
/*
* Another way to check if two Strings are anagram or not in Java
* This method assumes that both word and anagram are not null and lowercase
* #return true, if both Strings are anagram.
*/
public static boolean iAnagram(String word, String anagram){
char[] charFromWord = word.toCharArray();
char[] charFromAnagram = anagram.toCharArray();
Arrays.sort(charFromWord);
Arrays.sort(charFromAnagram);
return Arrays.equals(charFromWord, charFromAnagram);
}
public static boolean checkAnagram(String first, String second){
char[] characters = first.toCharArray();
StringBuilder sbSecond = new StringBuilder(second);
for(char ch : characters){
int index = sbSecond.indexOf("" + ch);
if(index != -1){
sbSecond.deleteCharAt(index);
}else{
return false;
}
}
return sbSecond.length()==0 ? true : false;
}
}

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.

JavaME: Convert String to camelCase

What would be a simple implementation of a method to convert a String like "Hello there everyone" to "helloThereEveryone". In JavaME support for String and StringBuffer utility operations are quite limited.
Quick primitive implementation. I have no idea of restrictions of J2ME, so I hope it fits or it gives some ideas...
String str = "Hello, there, everyone?";
StringBuffer result = new StringBuffer(str.length());
String strl = str.toLowerCase();
boolean bMustCapitalize = false;
for (int i = 0; i < strl.length(); i++)
{
char c = strl.charAt(i);
if (c >= 'a' && c <= 'z')
{
if (bMustCapitalize)
{
result.append(strl.substring(i, i+1).toUpperCase());
bMustCapitalize = false;
}
else
{
result.append(c);
}
}
else
{
bMustCapitalize = true;
}
}
System.out.println(result);
You can replace the convoluted uppercase append with:
result.append((char) (c - 0x20));
although it might seem more hackish.
With CDC, you have:
String.getBytes();//to convert the string to an array of bytes
String.indexOf(int ch); //for locating the beginning of the words
String.trim();//to remove spaces
For lower/uppercase you need to add(subtract) 32.
With these elements, you can build your own method.
private static String toCamelCase(String s) {
String result = "";
String[] tokens = s.split("_"); // or whatever the divider is
for (int i = 0, L = tokens.length; i<L; i++) {
String token = tokens[i];
if (i==0) result = token.toLowerCase();
else
result += token.substring(0, 1).toUpperCase() +
token.substring(1, token.length()).toLowerCase();
}
return result;
}
Suggestion:
May be if you can port one regexp library on J2ME, you could use it to strip spaces in your String...
Try following code
public static String toCamel(String str) {
String rtn = str;
rtn = rtn.toLowerCase();
Matcher m = Pattern.compile("_([a-z]{1})").matcher(rtn);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1).toUpperCase());
}
m.appendTail(sb);
rtn = sb.toString();
return rtn;
}
I would suggest the following simple code:
String camelCased = "";
String[] tokens = inputString.split("\\s");
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
camelCased = camelCased + token.substring(0, 1).toUpperCase() + token.substring(1, token.length());
}
return camelCased;
I would do it like this:
private String toCamelCase(String s) {
StringBuffer sb = new StringBuffer();
String[] x = s.replaceAll("[^A-Za-z]", " ").replaceAll("\\s+", " ")
.trim().split(" ");
for (int i = 0; i < x.length; i++) {
if (i == 0) {
x[i] = x[i].toLowerCase();
} else {
String r = x[i].substring(1);
x[i] = String.valueOf(x[i].charAt(0)).toUpperCase() + r;
}
sb.append(x[i]);
}
return sb.toString();
}
check this
import org.apache.commons.lang.WordUtils;
String camel = WordUtils.capitalizeFully('I WANT TO BE A CAMEL', new char[]{' '});
return camel.replaceAll(" ", "");

Resources