I have a string tajmahal.txt sarjan.pdf noorjahan.exe. I want to store this string in a string array such that ar[0] = tajmahal.txt, ar[1] = sarjan.pdf and ar[2] = noorjahan.exe. How can I do it without using any build functions in java (because I am using j2me which does not support many j2se functions). Any help would be great. Thanks in advance.
Since String.split is not available. You can see the implementation of split from this answer
public static String[] Split(String splitStr, String delimiter) {
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
// split
char[] chars = splitStr.toCharArray();
for (int i=0; i < chars.length; i++) {
if (delimiter.indexOf(chars[i]) != -1) {
// we bumbed into a delimiter
if (token.length() > 0) {
tokens.addElement(token.toString());
token.setLength(0);
}
} else {
token.append(chars[i]);
}
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i=0; i < splitArray.length; i++) {
splitArray[i] = (String)tokens.elementAt(i);
}
return splitArray;
}
String str="tajmahal.txt sarjan.pdf noorjahan.exe";
StringTokenizer st=new StringTokenizer(str," ");
String[] arr=new String[st.countTokens()];
int i=0;
while (st.hasMoreElements()){
arr[i]=st.nextToken();
i++;
}
There are implementations of StringTokenizer in J2me.
check out this example to help you out with the task.
StringTokenizer token;
token = new StringTokenizer(str);
int i=0;
while(token.hasMoreElements()){
ar[i++]= tok.nextToken();
}
It depends on which Java ME configuration/profile set you use.
When it comes to CLDC/MIDP, where there is no collections, StringTokenizer, split(), and so on.
count those space(' ')s first.
prepare a String[count + 1].
split each token while buffering characters with a StringBuffer.
static String[] split(final String string) {
// count spaces
int spaces = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == 0x20) {
spaces++;
}
}
// prepare the array and buffer
final String[] split = new String[spaces + 1];
final StringBuffer buffer = new StringBuffer();
int index = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == 0x20) {
split[index++] = buffer.toString();
buffer.delete(0, buffer.length());
continue;
}
buffer.append(string.charAt(i));
}
return split;
}
Related
I have the following assignment that I succeeded, however the code is very inefficient, I would appreciate if someone could show me a more efficient way, perhaps with substring. the assignment:
/**
* Separates a given string into tokens, which are the "words" that are
* separated by one or more occurrences of the given separator character.
* Returns the tokens as an array of String values.
*/
public static String[] tokenize (String str, char separator) {
// Removes all the occurrences of the separator at the beginning and end of str
String source = trim(str, separator);
String[] tokens = new String[charRunCount (source,separator)+1];
String tmp = ""; // a string in order to take a word, then run over this string
int j = 0;
int i = 0;
while (i < tokens.length) {
if ( source.charAt (j) != separator ) {
do {
tmp += source.charAt (j);
if ( j >= source.length () - 1 ) {
break;
}
else { // so that we math the source length
j++;
}
} while (source.charAt (j) != separator);
}
if ( source.charAt (j) == separator ) {
j++;
while (source.charAt (j) == separator) {
j++;
}
}
tokens[i] = tmp;// taking the token into place
tmp = ""; //resetting the token so we can begin anew
i++;
}
return tokens;
}
the cahrRunCount function:
public static int charRunCount(String str, char c){
char last = 0;
int counter = 0;
for (int i = 0; i < str.length(); i++) {
// whenever a run starts.
if (last != c && str.charAt(i) == c) {
counter++;
}
last = str.charAt(i);
}
return counter;
}
I cannot use import or regex, thank you!
Use String.split method
String[] tokens = str.split(separator)
for(String token:tokens){
//your code goes here
}
Docs here
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
If you want, you can use the split method of the String class (just like #Amidala Siva Kumar suggested), like this:
public static String[] tokenize (String str, char separator) {
String[] tokens = str.split(separator);
return tokens;
}
Or, if you want to do it using your own split, you may do it like this (an improvement to your code).
public static String[] tokenize (String str, char separator) {
String sep = ""+separator;
int max_size = str.length() - str.replace(sep, "").length() +1 ; // Calculate max array size
String[] temp = new String[max_size];
int start = 0, index = 0, exact_size = 0;
int pos = str.indexOf(separator);
while (pos>=start) {
if (pos>start){
temp[index++] = str.substring(start,pos).trim();
exact_size++;
}
start = pos + 1;
pos = str.indexOf(separator,start);
}
String[] tokens = new String[exact_size];
System.arraycopy(temp, 0, tokens, 0, exact_size);
return tokens;
}
Hope you find it useful.
I get an error for String[] t = words.split("_"); using jdk 1.3 in intelliJ
Error:(133, 51) java: cannot find symbol
symbol: method split(java.lang.String)
location: variable words of type java.lang.String
I have to use this SDK because the project is old, I tried jdk 1.4 but had many other errors, then I decided to replace the above code with something that can be complied using jdk 1.3.
What is the function for that?
The following piece of code seems to be working fine for me.
However, I have assumed that the delimiter on the basis of which you need to split is only a single character.
public static void main(String[] args){
String string = ",alpha,beta,gamma,,delta";
String[] wordsSplit = splitByDelimiter(string, ",");
for(int i=0; i<wordsSplit.length; i++){
System.out.println("-"+wordsSplit[i]+"-");
}
}
public static String[] splitByDelimiter(String fullString, String delimiter){
// Calculate number of words
int index = 0;
int[] delimiterIndices = new int[fullString.length()];
int wordCount = 0;
do{
if(delimiter.equals(fullString.charAt(index)+"")){
delimiterIndices[wordCount++] = index;
}
index++;
} while(index < fullString.length());
// Correction for strings not ending in a delimiter
if(!fullString.endsWith(delimiter)){
delimiterIndices[wordCount++] = fullString.length();
}
// Now create the words array
String words[] = new String[wordCount];
int startIndex = 0;
int endIndex = 0;
for(int i=0; i<wordCount; i++){
endIndex = delimiterIndices[i];
words[i] = fullString.substring(startIndex, endIndex);
startIndex = endIndex+1;
}
return words;
}
Alternate solution:
public static ArrayList splitByDelimiter(String fullString, String delimiter){
fullString += delimiter; //
ArrayList words = new ArrayList();
int startIndex = 0;
int endIndex = fullString.indexOf(delimiter); //returns first occurence
do{
words.add(fullString.substring(startIndex, endIndex));
startIndex = endIndex+1;
endIndex = fullString.indexOf(delimiter, startIndex);
} while(endIndex != -1);
return words;
}
public String[] split(String regex) was introduced in Java 1.4
So you could use your own implementation using StringTokenizer(String str, String delim) which was introduced in Java 1.0
List list = new ArrayList();
StringTokenizer st = new StringTokenizer("this_is_a_test", "_");
while (st.hasMoreTokens()) {
list.add(st.nextToken());
}
//[this, is, a, test]
Further if you want final result as an Array, you can use
String[] t = list.toArray(new String[0]);
You will either have to use StringTokenizer, a combination of indexOf() and substring(), or something you make on your own.
You could go with the C approach, which is: implement it yourself.
Here is a possible implementation, it now returns all elements, might need some tweaks:
int length;
int split_amount = 0;
String temp = new String("This_takes_into_consideration_something_something_test");
char split = '_';
for(int i = 0; i<length;i++){
if(temp.charAt(i) == split ){
split_amount++;
}
}
split_amount++;
String[] result = new String[split_amount];
int j = 0;
for(int i = 0; i<split_amount; i++){
result[i] = "";
boolean t = true;
for(; j<length && t ;j++){
if(temp.charAt(j) == split){
t = false;
break;
}
result[i] += temp.charAt(j);
}
j++;
}
Maybe a simple solution is:
String words = "this_is_a_test";
StringTokenizer st0 = new StringTokenizer(words, "_");
String[] t = new String[st0.countTokens()];
int k = 0;
while(st0.hasMoreTokens()){
String tmp0 = st0.nextToken();
t[k] = tmp0;
k++;
}
I have requirement to print String buffer lines as last to first order.
Example :toString of Stringbuffer method is printing below output:
this
is
some
text
Desired output:
text
some
is
this
What you could do is to create an array, iterate over it.
String s = new String("this\nis\nsome\ntext");
String []tokens = s.split("\n");
for(int i = tokens.length - 1; i >= 0; --i)
System.out.println(tokens[i]);
StringBuffer s = new StringBuffer("this\nis\nsome\ntext");
String []tokens = s.toString().split("\n");
for(int i = tokens.length - 1; i >= 0; --i)
System.out.println(tokens[i]);
A better memory less approach would be.
StringBuffer s = new StringBuffer("this\nis\nsome\ntext");
String word = "";
for(int i = s.length() - 1; i >= 0; --i)
{
if(s.charAt(i) != '\n')
{
word = s.charAt(i) + word;
}
else{
System.out.println(word);
word = "";
}
}
if(!word.equals(""))
System.out.println(word);
StringBuffer is a final class so you cannot extend it and override its toString() method to achieve what you want to do. You will have to handle it in your code.
you will have to do something like this :
public class Reverse {
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer s =new StringBuffer();
s.append("this\nis\nsome\ntext");
String[] rev = s.toString().split("\n");
for(int i=rev.length-1;i>=0;i--) {
System.out.println(rev[i]);
}
}
}
o/p :
text
some
is
this
Hope that helps
StringBuffer does not, by itself, have the capacity to return the lines the way you want them. You can either get the whole string from the buffer and use string.split("\n") to split it into an array, which you can then iterate over back to front, or create a class of your own that provides a function that handles such an operation
This should probably do it:
String[] lines = myStringBuffer.toString().split(System.lineSeparator()); //or use any other character for splitting
for(int i=lines.length; i>0; i--) {
System.out.println(lines[i-1]);
}
StringBuffer or String also has a lastIndexOf.
StringBuffer buf = new StringBuffer("this\nis\nsome\ntext");
final String EOL = "\n"; // Or "\r\n" or even "\u0085".
for (int pos = buf.length(); pos > 0; ) {
int before = buf.lastIndexOf(EOL, pos);
before = before == -1 ? 0 : before + EOL.length();
String line = buf.substring(before, pos);
System.out.println(buf);
pos = before - EOL.length();
}
Note: StringBuilder is better.
I have a large stringbuffer which i would like to break into smaller parts. The string buffer looks like this
"name1+name2+name3+name4+..........+name2000"
Where
name1=john
name2=prince
and so on.
(You get the idea.name1,name2,name3 stand for actual names of varying length)
Now i would like to store the names in a string array with each positon containing a 200 names.
string[0]="name1+name2+name3+........+name200";
string[1]="name201+name202+...."
How would i go about achieving this task?
StringTokenizer str = new StringTokenizer(<StringBufferObject>);
int count = 0;
int arrCount = 0;
StringBuffer temp;
String[] stringArr = new String[x];
while(str.hasMoreTokens()) {
count++;
if(count != 200) {
temp.append(str.nextToken());
}
else {
stringArr[arrCount] = temp;
temp.delete(0,temp.length());
count = 0;
arrCount++;
}
It would be a lot easier to split a String using String.split() if that's possible:
/* something like this */
String arrayOfStrings = inputString.split("\+");
If you have to keep it as a StringBuffer you'll have to loop over the input and tokenize it yourself.
I guess it would look something like this:
public String[] getTwoHundredStrings(StringBuffer inputBuff, String someToken)
{
String [] nameArray = new String [200];
int currentPos = 0;
int nextPos = 0;
for ( int i = 0; i < 200; i ++ ) {
nextPos = inputBuff.indexOf(someToken, currentPos);
if ( nextPos < 0 ) {
break;
}
String nextName = inputBuff.substring(currentPos, nextPos);
nameArray[i] = nextName;
currentPos = nextPos;
}
/* do some cleanup if nameArray has less than 200 elements */
return nameArray;
You must have some delimiter between each name. To break the string we should have some delimiter.
If you have delimiter you can use subString() in for loop.
try to use
String[] tempNames = new String(namesBuffer).split("+");
and then
int length = (tempNames.length / 200)+ (tempName.length % 200)
String[] names = new String[length];
for(int i = 0 ; i< tempNames.length ; i++){
for(int j = 0 ; j < length ; j++)
names[j] = tempNames[i];
}
hope this helps
Split on "+", using String.split("\\+")
Get chucks, in smaller arrays, Arrays.copyOfRange(...)
Join using Guava Joiner like Joiner.on("+").join(smallerArray)
J2ME String Tokenizer:
public String[] split(String toSplit, char delim, boolean ignoreEmpty) {
StringBuffer buffer = new StringBuffer();
Stack stringStack = new Stack();
for (int i = 0; i < toSplit.length(); i++) {
if (toSplit.charAt(i) != delim) {
buffer.append((char) toSplit.charAt(i));
} else {
if (buffer.toString().trim().length() == 0 && ignoreEmpty) {
} else {
stringStack.addElement(buffer.toString());
}
buffer = new StringBuffer();
}
}
if (buffer.length() != 0) {
stringStack.addElement(buffer.toString());
}
String[] split = new String[stringStack.size()];
for (int i = 0; i < split.length; i++) {
split[split.length - 1 - i] = (String) stringStack.pop();
}
stringStack = null;
buffer = null;
return split;
}
Method Used To Call It:
String toSplit = myThreadObject.GetInfo();
String del = DelimiterValue.getString();
char delimiter = del.charAt(0);
String[] result = split(toSplit, delimiter, false);
if (result != null) {
for (int i = 0; i < result.length; i++) {
System.out.println("The elements are: " + result[i]);
}
} else {
System.out.println("The result is empty");
}
This is an example of how to split up a string in J2ME, it is actually splitting up html content from a website pulled in a thread.
Can anyone tell me how I add a simple counter into this code to count the number of times the result is printed out, i.e. how many tokens there are? Because i am struggling.
Many thanks
No need to add a counter as the array has the public .length property which exposes the count for you. I added one line to your code (and a comment immediately before it). I also removed your check for result != null because your split() method will never return null. It returns a zero length array if there are no matches.
String toSplit = myThreadObject.GetInfo();
String del = DelimiterValue.getString();
char delimiter = del.charAt(0);
String[] result = split(toSplit, delimiter, false);
// add the line below:
System.out.println("There are " + result.length + " results");
for (int i = 0; i < result.length; i++) {
System.out.println("The elements are: " + result[i]);
}