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.
Related
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 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;
}
Hi I am trying to reverse a String to make a palindrome. Can someone please give me a tutorial on how to reverse a string? I have read some tutorials online and I have tried applying them to the palindrome program that i am writing but have not been successful.
import java.util.Random;
public class IterativePalindromGenerator {
public static void main(String[] args) {
Random random = new Random();
int floorValue = 1;
int cielingValue = 20;
int randomNumber = random.nextInt(cielingValue - floorValue)
+ floorValue;
String alphabetLetters = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < randomNumber; i++) {
char generatedLetters = alphabetLetters.charAt(random
.nextInt(alphabetLetters.length()));
String generatedLetterSTRINGType = Character
.toString(generatedLetters);// converts char to string
System.out.print(generatedLetterSTRINGType);
}
}
}
To reverse a string you can use StringBuffers reverse() method:
public String reverse(String stringToReverse) {
return new StringBuffer(stringToReverse).reverse().toString();
}
Hey here is my code from a college course. Our task was to implement a recursive procedure. Hope this can help the community.
package DiskreteMathe;
import java.util.*;
public class AufgabePalindromTestRekursiv {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter text here:");
String text= sc.next();
System.out.println(testPalindrom(text));
}
public static boolean testPalindrom (String text){
if (text.length()==2 && text.charAt(0)==text.charAt(1) || text.length()==1)
return true;
if(text.charAt(0)!=text.charAt(text.length()-1)){
return false;
} else {
text = text.substring(1, text.length()-1);
return testPalindrom(text);
}
}
}
When creating a palindrome for existing string, you need to think of the cases of even and odd outcome strings. For example, if you input String "abc", you should expect there are two outcome palindrome strings: abccba (even) and abcba (odd).
Here is my code:
public class PalindromeGenerator {
public static void main(String[] args) {
String str = "abc";
String reverse_str = "";
for (int n = str.length(); n>0; n--){
reverse_str += str.substring(n-1, n);
}
String even_str = str + reverse_str;
String odd_str = str.substring(0, str.length()-1) + reverse_str;
System.out.println(even_str); // print "abccba"
System.out.println(odd_str); //print "abcba"
}
}
I Hope this can help you.
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();
}
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(" ", "");