Dividing a StringBuffer into smaller parts - java

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)

Related

saving random letters of an array as a String

I wanna write a program in which different letters of a String Array form different words based on random orders. The most important part is that letters should not be duplicate in one word. I could somehow make the correct pattern but the problem is that I can only show them on console and couldn't find a way to save them as a String (like "OMAN"). Here is my code :
int size = 4;
ArrayList<Integer> list = new ArrayList<Integer>(size);
Random rnd = new Random();
while (list.size()<size) {
int random = rnd.nextInt(size);
if (!list.contains(random)) {
list.add(random);
}
}
String[] words = {"M","O","A","N"};
for(int i=0 ; i<size ; i++){
System.out.println(words[list.get(i)]);
}
You could accumulate them to a StringBuilder:
StringBuilder sb = new StringBuilder(size);
for(int i = 0 ; i < size ; i++) {
sb.append(words[list.get(i)]);
}
String result = sb.toString();
First declare a blank string
String answer = "";
Then in your for loop do
answer+=words[list.get(i)];
When you leave the for loop
System.out.println(answer);
Will have what you want. To do it more efficiently I'd read up on StringBuilder.
You can do something like this,
int size = 4;
ArrayList<Integer> list = new ArrayList<Integer>(size);
Random rnd = new Random();
while (list.size() < size) {
int random = rnd.nextInt(size);
if (!list.contains(random)) {
list.add(random);
}
}
String[] words = {"M", "O", "A", "N"};
String finalWord = "";
for (int i = 0; i < size; i++) {
finalWord += words[list.get(i)];
}
System.out.println(finalWord);

Java split in jdk 1.3

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

How to print String buffer lines from last to first order

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.

Store parts of string in a string array

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

Split string by char in java

I'm getting a string from the web looking like this:
Latest Episode#04x22^Killing Your Number^May/15/2009
Then I need to store 04x22, Killing Your Number and May/15/2009 in diffent variables, but it won't work.
String[] all = inputLine.split("#");
String[] need = all[1].split("^");
show.setNextNr(need[0]);
show.setNextTitle(need[1]);
show.setNextDate(need[2]);
Now it only stores NextNr, with the whole string
04x22^Killing Your Number^May/15/2009
What is wrong?
String.split(String regex)
The argument is a regualr expression, and ^ has a special meaning there; "anchor to beginning"
You need to do:
String[] need = all[1].split("\\^");
By escaping the ^ you're saying "I mean the character '^' "
If you have a separator but you don't know if it contains special characters you can use the following approach
String[] parts = Pattern.compile(separator, Pattern.LITERAL).split(text);
Using guava, you can do it elegantly AND fast:
private static final Splitter RECORD_SPLITTER = Splitter.on(CharMatcher.anyOf("#^")).trimResults().omitEmptyStrings();
...
Iterator<String> splitLine = Iterables.skip(RECORD_SPLITTER.split(inputLine), 1).iterator();
show.setNextNr(splitLine.next());
show.setNextTitle(splitLine.next());
show.setNextDate(splitLine.next());
public static String[] split(String string, char separator) {
int count = 1;
for (int index = 0; index < string.length(); index++)
if (string.charAt(index) == separator)
count++;
String parts[] = new String[count];
int partIndex = 0;
int startIndex = 0;
for (int index = 0; index < string.length(); index++)
if (string.charAt(index) == separator) {
parts[partIndex++] = string.substring(startIndex, index);
startIndex = index + 1;
}
parts[partIndex++] = string.substring(startIndex);
return parts;
}
String input = "Latest Episode#04x22^Killing Your Number^May/15/2009";
//split will work for both # and ^
String splitArr[] = input.split("[#\\^]");
/*The output will be,
[Latest Episode, 04x22, Killing Your Number, May/15/2009]
*/
System.out.println(Arrays.asList(splitArr));

Categories