I am trying to implement a custom split string method and I am getting lost in for loops. I will post my code so far and hopefully someone can tell me where I am going wrong. I know there are better ways to do this, but I am just wondering why I can't seem to get the for loops to read properly. Basically I want to be able to set multiple delimiters at once. So I was populating a an array of just the delimiters and trying to compare each character in the full string with each entry in the delimiter Array. If it was not a delimiter, it added it to a string, if it was, it broke off the loop and took the string it created and added it to the first entry in the string array. This should continue until the character array was done.
Here is my code:
String[] charArray = new String[s.length()];
String[] stringArray = new String[s.length()];
String[] delimArray = new String[regex.length()];
// Fill array with delimiter values
for (int i=0; i < delimArray.length; i++) {
delimArray[i] = Character.toString(regex.charAt(i));
}
// Fill array with all values in string by character
for (int i=0; i < charArray.length; i++) {
charArray[i] = Character.toString(s.charAt(i));
}
for (int i=0; i < stringArray.length; i++) {
String s1 = "";
for (int k=0; k < charArray.length; k++) {
for (int j=0; j < delimArray.length; j++) {
if (charArray[k] != delimArray[j]) {
s1 = s1 + charArray[k];
} else if (charArray[k] == delimArray[j]) {
stringArray[i+1] = delimArray[j];
break;
}
}
s1 = s1 + charArray[k];
}
stringArray[i] = s1;
}
Try this-
public static String[] split(String string, String delem) {
ArrayList<String> list = new ArrayList<String>();
char[] charArr = string.toCharArray();
char[] delemArr = delem.toCharArray();
int counter = 0;
for (int i = 0; i < charArr.length; i++) {
int k = 0;
for (int j = 0; j < delemArr.length; j++) {
if (charArr[i+j] == delemArr[j]) {
k++;
} else {
break;
}
}
if (k == delemArr.length) {
String s = "";
while (counter < i ) {
s += charArr[counter];
counter++;
}
counter = i = i + k;
list.add(s);
//System.out.println(" k = "+k+" i= "+i);
}
}
String s = "";
if (counter < charArr.length) {
while (counter < charArr.length) {
s += charArr[counter];
counter++;
}
list.add(s);
}
return list.toArray(new String[list.size()]);
}
Try this:-
String regex = "";
String[] charArray = new String[s.length()];
String[] stringArray = new String[s.length()];
char[] delimArray = new char[regex.length()];
// Not required as you can directly use regex.charAt(i)
// Fill array with delimiter values
/*for (int i=0; i < delimArray.length; i++) {
delimArray[i] = regex.charAt(i);
}
*/
// Not required as you can directly use s.charAt(i)
// Fill array with all values in string by character
/*for (int i=0; i < charArray.length; i++) {
charArray[i] = Character.toString(s.charAt(i));
}*/
int i = 0;
// Outer loop
outer:
for (int k=0; k < s.length(); k++) {
// Inner loop
inner :
for (int j=0; j < delimArray.length; j++) {
// The if checks the current character in the string with each delimiter character and proceeds till it checks all the delimiters
if (s.charAt(k) != regex.charAt(j)) {
continue inner;
} else {
// If the current character is a delimiter then donot add it to the final string array result
i++;
continue outer;
}
}
// This if is to avoid null being appended to the string
if(stringArray[i] == null) {
stringArray[i] = "";
}
// Add the character(since it is not a delimiter) to the current index i
stringArray[i] += Character.toString(s.charAt(k));
}
//}
EDITED ANSWER:-
String s = "ab#12#45-3";
System.out.println(s.matches("\\d+"));
String regex = "-#";
String[] charArray = new String[s.length()];
String[] stringArray = new String[s.length()];
char[] delimArray = new char[regex.length()];
// Not required as you can directly use regex.charAt(i)
// Fill array with delimiter values
/*for (int i=0; i < delimArray.length; i++) {
delimArray[i] = regex.charAt(i);
}
*/
// Not required as you can directly use s.charAt(i)
// Fill array with all values in string by character
/*for (int i=0; i < charArray.length; i++) {
charArray[i] = Character.toString(s.charAt(i));
}*/
int i = 0;
// Outer loop
outer:
for (int k=0; k < s.length(); k++) {
// Inner loop
inner :
for (int j=0; j < delimArray.length; j++) {
// The if checks the current character in the string with each delimiter character and proceeds till it checks all the delimiters
if (s.charAt(k) != regex.charAt(j)) {
continue inner;
} else {
// Else block is reached when any of the character in the string is a delimiter
// Check if the current array position is null(which means nothing is assigned so far) and move to the next position only if it is not null
if(stringArray[i] != null) {
i++;
}
// Assign the delimiter in the output array
stringArray[i] = Character.toString(s.charAt(k));
// Increment to the next position in the array
i++;
continue outer;
}
}
// This if is to avoid null being appended to the string
if(stringArray[i] == null) {
stringArray[i] = "";
}
// Add the character(since it is not a delimiter) to the current index i
stringArray[i] += Character.toString(s.charAt(k));
}
//}
/*
* To avoid nulls in the final split array we need to initialize one more array
* and assign only valid values to the final split array
*/
String[] splitStrArr = new String[i+1];
int m = 0;
do {
splitStrArr[m] = stringArray[m];
m++;
} while (m <= i);
Related
only allow charAt method and length method . Thank you so much!
void runApp() {
String str = "345, 688"; //->"345" "688"
String value = strCut(str);
}
String strCut(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(3) == ',') {
what should i write here ? ?
}
Your code needs some refactoring, try this:
void runApp() {
String str = "345, 688"; //->"345" "688"
String value = strCut(str);
}
String strCut(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
int cutStringIndex;
if (str.charAt(i) == ',') {
cutStringIndex = i;
}
for (int i = 0; i < cutStringIndex(); i++) {
String cutStringOne = "";
cutStringOne = cutStringOne + str.charAt(i);
}
for (int i = cutStringIndex() + 1; i < str.length(); i++) {
String cutStringTwo = "";
cutStringTwo = cutStringTwo + str.charAt(i);
}
cutString = cutStringOne + " " + cutStringTwo;
return cutString;
}
This will take out the comma which appears to be what you were looking for. I only used the two methods you asked for. Essentially this code gets the index of the comma, then reconstructs the two parts of the strings until it reaches the point of the comma, and skips over it. It may need some minor tweaks for your situation but this should be what you're looking for.
It can be done like this, Suppose String s="200,300,450,600" and you have to split given string using charAt() and string.length() method then first add ',' at the end of the string as given in the code below.
String s="200,300,450,600,",str="";
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(ch!=','){ //checking if particular character is not ','
str+=ch; //storing it in str string
}
else{
System.out.println(str); //printing each string before ',' is found
str="";
}
}
The output of above code will be:200
300
450
600(all the numbers will be printed on next line)
If you want to use only charAt and string.length() then you should try this
void runApp{
String str = "345, 688, 123";
String values[] = strCut(str); //values[0] = 345, values[1] = 688, values[2] = 123
for(String value : values){
System.out.print(value + " ");
}
}
String[] strCut(String str) {
int elements = 1;
int index = 0;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == ',')
elements++;
}
String result[] = new String[elements];
for(int i = 0; i < result.length; i++)
result[i] = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != ',') {
if(str.charAt(i) != ' ')
result[index] = result[index] + str.charAt(i);
}
else index++;
}
return result;
}
You can do it as follows:
public class Main {
public static void main(String[] args) {
// Test
runApp();
}
static void runApp() {
String str = "345, 688"; // Expected->"345" "688"
String value = strCut(str);
System.out.println(value);// Display the result
}
static String strCut(String str) {
// Initialise result with a "
String result = "\"";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',') {// Check char at the index, i
// Add " at the end of one number and again " at the start of the next
result += "\" \"";
} else if (str.charAt(i) != ' ') {
result += str.charAt(i);
}
}
// Add " at the end
result += "\"";
// Finally, return result
return result;
}
}
Output:
"345" "688"
if you must want to make use of charAt() then do like below..
ArrayList<String> stringArr= new ArrayList<String>();
int startindex=0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ',')
{
String partString = str.substring(startindex, i) ;
startindex=i+1;
stringArr.add(partString);
}
}
String lastString = str.substring(startindex, str.length()) ;
stringArr.add(lastString);
OR
You can simply use split method like below
String[] parts = string.split(",");
String part1 = parts[0]; // 345
String part2 = parts[1]; // 688
You can achieve it by simply doing this,
This will give you the desired result.
String str = "345,688";
ArrayList<String> stringArray = new ArrayList<>();
int startindex=0;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == ',') {
String subStr = str.substring(startindex, i);
startindex = i+1;
stringArray.add(subStr);
}
}
stringArray.add(str.substring(startindex));
I am new to programming I need to reverse a string without using the library function.
I am able to reverse but as expected.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
String rev = "";
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<String> splitResult = new ArrayList<String>();
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == ' ')
list.add(i);
list.add(0, 0);
list.add(list.size(), s.length());
String[] words = new String[list.size()];
for (int j = 0; j <= words.length - 2; j++)
splitResult.add(s.substring(list.get(j), list.get(j + 1)).trim());
System.out.println(splitResult);
String[] str = new String[splitResult.size()];
str = splitResult.toArray(str);
for (int i = 0; i < str.length; i++) {
if (i == str.length - 1) {
rev = str[i] + rev;
} else {
rev = " " + str[i] + rev;
}
}
System.out.println(rev);
Expected:
Input: i am coder
output: redoc ma i
actual
input: i am coder
output: coder am i
You can just provide an empty result variable, iterate the characters of the given String by using an enhanced for-loop (also known as for-each loop) setting every character to index 0 of the result variable by just concatenating the character to the result variable like this:
public static void main(String[] args) {
// input
String s = "I am coder";
// result variable for reverse input
String reverseS = "";
// go through every single character of the input
for (char c : s.toCharArray()) {
// and concatenate it and the result variable
reverseS = c + reverseS;
}
// then print the result
System.out.println(reverseS);
}
You can of course do that in a slightly different way using a classic for-loop and the length of the input, see this example:
public static void main(String[] args) {
String s = "I am coder";
String reverseS = "";
for (int i = 0; i < s.length(); i++) {
reverseS = s.charAt(i) + reverseS;
}
System.out.println(reverseS);
}
String s = "I am coder";
String rev="";
for (int i = s.length()-1; i >=0; i--) {
rev+=s.charAt(i);
}
System.out.println(rev);
I have set the index I to the last character of the given string and the condition is set to 0(i.e the first character). Hence the loop runs from the last character to the first character. It extracts each of the characters to a given new String. Hope it helps!
You can just take another list go from last to first and display like this
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
ArrayList<Character> working = new ArrayList<Character>();
ArrayList<Character> finished = new ArrayList<Character>();
for (char ch: s.toCharArray()) {
working.add(ch);
}
for(int i = working.size() - 1 ; i>=0 ; i--){
finished.add(working.get(i));
}
for(int j = 0 ; j < finished.size() ; j++){
System.out.print(finished.get(j));
}
I'm trying to write a code that take a string : (7+5)*(6+9)
and return the string : 7*6 + 7*9 + 5*6 + 5*9
my algorithm is to create 2 char arrays (for this example : 75,69)
and run in O^2 loop in this 2 arrays and copy value from first array , * value from second array, +. i get index of bounds exception and don't understand why.
this is my code :
String s = "((7+5)*(6+9))";
char[] ch = s.toCharArray();
char[] newCh = new char[30];
int j=0;
int blocks = 2;
int newi = 0;
for (int i=0 ; i<ch.length ; i++) {
if (ch[i]=='(' && ch[i+1]!='(') {
j=i+1;
while (blocks>0) {
if (ch[j]==')') {
blocks--;
newCh[newi]='-';
newi++;
}
if (ch[j]!='+' && ch[j]!='*' && ch[j]!=')' && ch[j]!='(') {
if (blocks==0) {
break;
}
else {
newCh[newi]=ch[j];
newi++;
}
}
j++;
}
}
continue;
}
System.out.println("new Char array : ");
for (int i=0 ; i<newCh.length ; i++) {
System.out.print(newCh[i]);
}
System.out.println();
Multy(newCh);
and my multy method :
public static char[] Multy(char[] ch) {
char[] newc = new char[50];
char[] c1 = new char[30];
char[] c2 = new char[30];
int newi = 0;
int i1 = 0;
int i2 = 0;
int flag = 0;
for (int i=0 ; i<ch.length ; i++) {
if (ch[i]!='-') {
if (flag ==0) {
c1[i1] = ch[i];
i1++;
}
else {
if (ch[i]!='-')
c2[i2]= ch[i];
i2++;
}
}
if (ch[i]=='-')
flag = 1;
}
System.out.println("In func");
System.out.print("c1 : ");
for (int i=0 ; i<c1.length ; i++) {
System.out.print(c1[i]);
}
System.out.println();
System.out.print("c2 : ");
for (int i=0 ; i<c1.length ; i++) {
System.out.print(c2[i]);
}
///////////
for (int i=0 ; i<c1.length ; i++) {
for (int j=0 ; j<c2.length ; j++) {
newc[newi]=c1[i];
newc[newi+1] = '*';
newc[newi+2] = c2[j];
newc[newi+3] = '+';
newi+=4;
}
}
System.out.print("NEWc2 : ");
for (int i=0 ; i<newc.length ; i++) {
System.out.print(newc[i]);
}
return newc;
}
in te double for loop you iterate to the end of the array (c1.length and c2.length) while you add to a number in the loop newc[newi+X] but because you loop to the end you will run out of places and you will get the IndexOutOfBoundsException...
for (int i=0 ; i<c1.length ; i++) {
for (int j=0 ; j<c2.length ; j++) {
newc[newi]=c1[i];
newc[newi+1] = '*';
newc[newi+2] = c2[j];
newc[newi+3] = '+';
newi+=4;
}
}
UPDATE:
Extra explanation :-)
If you do something like this:
public class ArrayExample {
public static void main(String[] args) {
String[] strings = new String[3];
System.out.println("strings.length = " + strings.length);
strings[4] = "foo";
}
}
The output will be:
strings.length = 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at nl.ivonet.ArrayExample.main(ArrayExample.java:26)
This is because I tried to assign a value at index 4 of the strings array, but the strings array was initialized with new String[3] giving it a fixed size of 3. That's what goes wrong and why your code failed.
An Array is not the same as a List. And Array is fixed size and a list not.
I am looking to implement a method to perform basic string compression in the form of:
aabcccccaaa -> a2b1c5a3
I have this program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(compress(str));
}
public static String compress(String str) {
char[] chars = str.toCharArray();
int count = 0;
String result = "";
for (int i = 0; i < chars.length; i++) {
char curr = chars[i];
result += curr;
for (int j = i; j < chars.length; j++) {
if (chars[j] == curr) {
count++;
}
else {
i += count;
break;
}
}
result += count;
count = 0;
}
return result;
}
}
But in my tests I am always missing the last character count.
I assume this is because the program gets out of the inner for loop before it should, but why is this the case?
Thanks a lot
You don't need two for loops for this and can do it in one go like so
String str = "aaabbbbccccca";
char[] chars = str.toCharArray();
char currentChar = str.length() > 0 ? chars[0] : ' ';
char prevChar = ' ';
int count = 1;
StringBuilder finalString = new StringBuilder();
if(str.length() > 0)
for(int i = 1; i < chars.length; i++)
{
if(currentChar == chars[i])
{
count++;
}else{
finalString.append(currentChar + "" + count);
prevChar = currentChar;
currentChar = chars[i];
count = 1;
}
}
if(str.length() > 0 && prevChar != currentChar)
finalString.append(currentChar + "" + count);
System.out.println(finalString.toString());
Output is: a3b4c5a1 for aaabbbbccccca
Keep a track of character that you are reading and compare it with next character of the string. If it is different, reset the count.
public static void stringCompression (String compression) {
String finalCompressedString = "";
char current = '1';
int count = 0;
compression = compression + '1';
for (int i = 0; i < compression.length(); i++) {
if (compression.charAt(i) == current) {
count = count + 1;
} else {
if (current != '1')
finalCompressedString = finalCompressedString + (current + Integer.toString(count));
count = 1;
current = compression.charAt(i);
}
}
System.out.println(finalCompressedString);
}
My answer for String Compression in java.
In this what i have done is and what you should have done is that , Keep a record of the characters that that are coming for a specific number of times, do so by comparing the current character with the next character , and when the current and the next character become unequal reset the value of count and repeat the whole process again for the next different character.
Hope it helps!
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int count = 0;
for (int i=0; i<str.length(); ++i) {
int j=i+1;
count=1;
while (j!=str.length() && str.charAt(i) == str.charAt(j)) {
count += 1;
j += 1;
i += 1;
}
System.out.print(str.charAt(i));
if (count > 1) {
System.out.print(count);
}
}
}
}
I have array
data[][];
convert to string:
string = Arrays.deepToString(data);
string:
[[1, 1394119227787, 59474093, USD/DKK, true, 0.05, 5.391582, 5.00663, 5.39663, null, null], [1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null],
[1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null],
[1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null]]
and How convert this string back to array?
Try my stringToDeep() method to convert back to Array.
import java.util.*;
public class DeepToArray {
public static void main(String[] args) {
int row, col;
row = 2;
col = 3;
String[][] in = new String[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
in[i][j] = i + " " + j;
}
}
String str = Arrays.deepToString(in);
System.out.println(str);
String[][] out = stringToDeep(str);
for (String s2[] : out) {
for (String s3 : s2) {
System.out.print(s3 + " ");
}
System.out.println();
}
}
private static String[][] stringToDeep(String str) {
int row = 0;
int col = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '[') {
row++;
}
}
row--;
for (int i = 0;; i++) {
if (str.charAt(i) == ',') {
col++;
}
if (str.charAt(i) == ']') {
break;
}
}
col++;
String[][] out = new String[row][col];
str = str.replaceAll("\\[", "").replaceAll("\\]", "");
String[] s1 = str.split(", ");
int j = -1;
for (int i = 0; i < s1.length; i++) {
if (i % col == 0) {
j++;
}
out[j][i % col] = s1[i];
//System.out.println(s1[i] + "\t" + j + "\t" + i % col);
}
return out;
}
}
There is no method in the java API that will automatically convert this back to an array. You could write code to do this yourself, but it would be tricky; this format does not escape special characters like the square brackets, or the commas. It might be easier just to use a format which is designed for encoding and decoding arrays, like JSON.
All the answers I found are 2-dimensional only, so here's my solution to reverse deepToString(...) for any number of dimensions:
Usage example:
String arrString = "[[[0.11695497071135137, 0.8830064157596283, 0.3433854446148375, 0.18825445694298526, 1.0441938749175883, 0.8941633746325311], [-0.089908138214512, 0.39821330927870574, 0.1365997500579524, 0.7008902956765364, 0.9897596683277262, 0.2847717055995359], [0.6450670283688857, 0.01516064860567864, -0.07904927386204857, 0.2703900981351612, 0.45402985012492075, 0.30505608337251183], [0.5122943117220898, 0.008726346575469023, 0.7734611917871235, 0.3051772999891666, 0.5237487372571624, 1.1824105144656751]]]";
String[][][] arr = (String[][][]) reverseDeepToString(arrString);
System.out.println(Arrays.deepToString(arr));
This code converts a string (arrString) into an array, and then the function Arrays.deepToString(...) converts it back into the same string.
Function code:
public static Object reverseDeepToString(String str){
int dimensions = 0;
for(int x = 0; x < str.length(); x++)
if(str.charAt(x) == '[')
dimensions++;
else break;
str = str.substring(dimensions, str.length() - dimensions);
return createArrayRecursive(str, dimensions);
}
private static Object createArrayRecursive(String str, int dimension){
if(dimension == 1)
return str.split(", "); // modify the code here if you want to convert the strings to another variable type
String[] s = str.split(getArraySeparator(dimension));
int[] lengths = new int[dimension];
lengths[0] = s.length;
Object arr = Array.newInstance(String.class, lengths); // and here (see comment above)
for(int x = 0; x < s.length; x++)
Array.set(arr, x, createArrayRecursive(s[x], dimension - 1));
return arr;
}
private static String getArraySeparator(int dimension){
String separator = ", ";
for(int x = 1; x < dimension; x++)
separator = ']' + separator + "\\[";
return separator;
}
Array to string and back to array :P
import java.util.Arrays;
import java.util.Random;
public class arrays {
public static void main(String [ ] args)
{
String[][] in = new String [10][4];
String[][] out = new String [10][4];
arrays nr = new arrays();
for(int i =0; i< 4; i++){
for(int j =0; j< 4; j++){
in[i][j] = nr.Rand(5);
}
}
System.out.println(Arrays.deepToString(in));
// tablica ok
// convert array to string
String line = "";
for(int i =0; i< 4; i++){
for(int j =0; j< 4; j++){
line += in[i][j] + "_";
}
line += ":";
}
System.out.println(line);
// line back to array
String[] xline = line.split(":");
int ss = 0;
for (String str : xline) {
out[ss] = (String[]) str.split("_");
System.out.println("string line>>>" + str);
ss++;
}
System.out.println(Arrays.deepToString(out));
}
public String nextSessionId() {
//private SecureRandom random = new SecureRandom();
//return new BigInteger(130, random).toString(32);
return null;
}
public String Rand(int zz){
char[] chars = "987654321abcdefghijklm111nopqrstuvwxyz0123456789".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < zz; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
// System.out.println(output);
return output;
}
}
:D