How to convert string of numbers into int array in java - java

I have an input String of "0102030405" how can I split this number by two so that it would have an output of String[] ("01", "02", "03", "04", "05").

Try this,
String a = "0102030405";
System.out.println(Arrays.toString(a.split("(?<=\\G.{2})")));

String input = "0102030405";
String[] output = new String[input.length()/2];
int k=0;
for(int i=0;i<input.length();i+=2){
output[k++] = input.substring(i, i+2);
}
for(String s:output){
System.out.println(s);
}

You could try something like reading each two characters from a string.
This could be solved by: "(?<=\\G.{2})"
But I think a cleaner solution is this:
string.substring(startStringInt, endStringInt);
Here is a complete example:
package Main;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
for (String part : splitString("0102030405", 2)) {
System.out.println(part);
}
}
private static List<String> splitString(String string, int numberOfChars) {
List<String> result = new ArrayList<String>();
for (int i = 0; i < string.length(); i += numberOfChars)
{
result.add(string.substring(i, Math.min(string.length(), i + numberOfChars)));
}
return result;
}
}

import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
HelloWorld h1 = new HelloWorld();
String a = "0102030405";
System.out.println(h1.getSplitString(a));
}
private ArrayList<String> getSplitString(String stringToBeSplitted) {
char[] charArray = stringToBeSplitted.toCharArray();
int stringLength = charArray.length;
ArrayList<String> outPutArray = new ArrayList<String>();
for(int i=0; i <= stringLength-2; i+=2){
outPutArray.add("" + charArray[i] + charArray[i+1]);
}
return outPutArray;
}
}
Here the String is first split into a char array. Then using a for loop two digits are concatenated and put into a ArrayList to return. If you need an Array to return you can change the return type to String[] and in the return statement change it to
outPutArray.toArray(new String[outPutArray.size()];
If you insert a string has odd number of characters last character will be omitted. Change the loop condition to fix that.

Related

split string input contains long numbers based on comma double quotes and brackets

I have a String like this
["1505213753057","1505213854042","1505537148455"]
I want to split it and store the values into Long Array.
String [] loanId = loanIds.split("\"?,(?=(?:(?:[^\"]*\"){2})*[^\"]*$)\"?");
Long[] data = new Long[loanId.length];
for (int i = 0; i < loanId.length; i++) {
data[i] = Long.parseLong(loanId[i]);
}
I am using this splitter but it is not working. Any help how to achieve this?
This should work
String loanIds = "[\"1505213753057\",\"1505213854042\",\"1505537148455\"]";
loanIds = loanIds.replaceAll("(\\[\")|(\"\\])", "").replaceAll("\",\"", ",");
String [] loanId = loanIds.split(",");
Long[] data = new Long[loanId.length];
for (int i = 0; i < loanId.length; i++) {
data[i] = Long.parseLong(loanId[i]);
System.out.println(data[i]);
}
Replace[ and ] with { and }.
import java.util.*;
class check {
public static void main(String ar[]){
String str[] ={"1505213753057","1505213854042","1505537148455"};
long ll[]=new long[str.length];
for(int i=0;i<str.length;i++)
ll[i]=Long.parseLong(str[i]);
for(int i=0;i<str.length;i++)
System.out.println(ll[i]);
}
}
This can be achieved using regex as shown below :
package com.grsdev.stackoverflow.question170920.pack01;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LongNumerString {
public static void main(String[] args) {
String text="[\"1505213753057\",\"1505213854042\",\"1505537148455\"]";
Pattern pattern=Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
List<Long> list=new ArrayList<>();
while(matcher.find()){
list.add(Long.valueOf(matcher.group()));
}
System.out.println("longs : "+list);
Long [] array = new Long[list.size()];
list.toArray(array);
}
}
mainstring=["1505213753057","1505213854042","1505537148455"]
Is this your String ?
If yes and u want to store all elements in long Array,then this myt be the solution
String stringWithoutBraces=mainstring.substring(1, mainstring.length()-1);
List<Long> loanidlist=new ArrayList<>();
String[] stringWithoutCommas=stringWithoutBraces.split(",");
for(String splited:stringWithoutCommas){
String eachElement=splited.substring(1,splited.length()-1);
loanidlist.add(Long.parseLong(eachElement));
}
Long[] loanid=(Long[]) loanidlist.toArray(new Long[loanidlist.size()]);

How can i split up an ArrayList of strings between letters and numbers WITHOUT using the split method?

To take an arraylist of strings consisting of strings like:
fewf5677
kskfj654
pqoen444
mgnwo888
And i want to split them up BUT i DON'T want to use the split method because I have to perform other calculations with the letters that i'have split up.
SO i'have decided to use the subList method. But I can't seem to find a proper example of implementing this correctly. Take a look at my code. Below is a method that takes in an arraylist of strings as the parameter:
public static void splitup(ArrayList<String> mystrings){
mystrings.subList(String[] letters, double numbers);
}
So overall, how do I take each string of letters and numbers and store them into their own string arrays? For example, i want
fewf
kskfj
pqoen
mgnwo
to be in their own string along with
5677
654
444
888
to be their own numbers.
You could use regex as seen in this answer and then check for a pattern as shown in this answer as follows:
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringSplitter {
public static void main(String[] args) {
ArrayList<String> myStringsList = new ArrayList<String>();
ArrayList<String> stringsList = new ArrayList<String>();
ArrayList<String> numbersList = new ArrayList<String>();
myStringsList.add("fewf5677");
myStringsList.add("kskfj654");
myStringsList.add("pqoen444");
myStringsList.add("mgnwo888");
for (String s : myStringsList) {
String splittedString[] = s.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
for (String string : splittedString) {
Matcher match = Pattern.compile("[0-9]").matcher(string);
if (match.find()) {
numbersList.add(string);
} else {
stringsList.add(string);
}
}
}
for (String s : numbersList) {
System.out.println(s);
}
for (String s : stringsList) {
System.out.println(s);
}
}
}
This will output:
5677
654
444
888
fewf
kskfj
pqoen
mgnwo
Remember that split() takes a regex as parameter, not a String and so, you can do something like the above code to get the desired output.
What you are trying to do is a bit strange. Why are you trying to overload subList method?
One of possible examples of what you could do is to iterate over mystrings list and separate each string into two variables.
http://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/
If you are familiar with regular expressions you can use them them.
If not you can iterate over string characters to separate letters from number.
http://java11s.blogspot.com/2012/02/java-program-to-separate-alphabets-and.html
Then add result to two separate lists List<String> and List<Double> (or probably List<Integers>) or create custom data structure.
You can try this way :
If we consider that the format of your input is a String in which you want to extract integers, then you should to test one element by one:
Main
public static void main(String[] a) {
List<String> myList = new ArrayList<>();
myList.add("fewf5677");
myList.add("kskfj654");
myList.add("pqoen444");
myList.add("mgnwo888");
List<String> listStrings = new ArrayList<>();
List<Integer> listIntegers = new ArrayList<>();
for (int i = 0; i < myList.size(); i++) {
listStrings.add(getStringPart(myList.get(i)));
listIntegers.add(Integer.parseInt(getIntegerPart(myList.get(i))));
}
System.out.println(listStrings);
System.out.println(listIntegers);
}
Get the string part of your element
private static String getStringPart(String str) {
String s = "";
for (int i = 0; i < str.length(); i++) {
if (!testInteger(str.charAt(i))) {
s += str.charAt(i);
} else {
break;
}
}
return s;
}
Get the Integer part of your element
private static String getIntegerPart(String str) {
String s = "";
for (int i = 0; i < str.length(); i++) {
if (testInteger(str.charAt(i))) {
s += str.charAt(i);
}
}
return s;
}
A method to check if your str is and Integer or not
private static boolean testInteger(char str) {
try {
Integer.parseInt(str+"");
return true;
} catch (Exception e) {
return false;
}
}
Output
[fewf, kskfj, pqoen, mgnwo]
[5677, 654, 444, 888]
Hope this can help you.

Duplicate Encoder codewars java Junit exception

I am doing a kata on Codewars named "Duplicate Encoder".
The code I have written does its job correctly, but junit(4.12) insists it does not for some reason. Both on the website and in my IDE (Eclipse). I have no idea why that is. Could someone shine some light on this issue? Thanks.
The class to be tested:
package com.danman;
import java.util.*;
public class Person {
static String encode(String word){
word = word.toLowerCase();
List<String> bank = new ArrayList<>();
StringBuilder wordTwo = new StringBuilder("");
//1: create a list of all unique elements in the string
for (int n = 0; n < word.length(); n++) {
String temp = word.substring(n, n+1);
if (temp.equals(" ")){continue;}
bank.add(temp);
}
for (int r = 0; r <word.length(); r++){
List<String> bankTwo = bank;
Iterator<String> it = bankTwo.iterator();
String tempTwo = word.substring(r, r+1);
int count = 0;
//2: iterate through the list of elements and append the appropriate token to the StringBuilder
while (it.hasNext()){
if (it.next().equals(tempTwo)){
++count;
}
}
if (count <= 1){
wordTwo.append("(");
} else {
wordTwo.append(")");
}`enter code here`
}
word = wordTwo.toString();
return word;
}
public static void main(String[] args) {
Person rinus = new Person();
System.out.println(rinus.encode("Prespecialized"));
}
Junit file:
package com.danman;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PersonTest {
#Test
public void test() {
assertEquals(")()())()(()()(", Person.encode("Prespecialized"));
assertEquals("))))())))", Person.encode(" ()( "));
}
As far as I understand your code, first assert is ok. I don't know why encoding " ()( " should return "))))())))". You iterate through bank list of characters in given string (spaces are excluded in that list), checking whether there is more than one occurence of each character from the word in the bank list. When you check if there is more than one space, the answer will be no, appending (, because count value will equal 0 (due to spaces being excluded from the bank list).
The second assert should rather be
assertEquals("((()()(((", Person.encode(" ()( "));
Maybe you need this
import java.util.ArrayList;
import java.util.Iterator;
public class DuplicateEncoder {
static String encode(String word) {
word=word.toUpperCase();
ArrayList<String> stack1 =new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder();
for(int i=0;i<word.length();i++){
String t = word.substring(i,i+1);
stack1.add(t);
}
for(int i=0;i<word.length();i++){
Iterator<String> iterator =stack1.iterator();
String t = word.substring(i,i+1);
int count=0;
while(iterator.hasNext()){
if(iterator.next().equals(t)){
count++;
}
}
if(count>1){
stringBuilder.append(")");
}
else stringBuilder.append("(");
}
word=stringBuilder.toString();
return word;}
public static void main(String[] args) {
encode("Pup");
}
}

Java occurrences of the given char in Array

This is my homework, I am trying to get the occurrences of 'e' in strings of the array.
My method doesn't seem to work. Can anyone wise person advise where did I go wrong?
import java.util.*;
import java.lang.*;
import java.io.*;
public class CountChar {
public static void main(String[] args) {
String[] strings
= {"hidden", "Java SDK", "DDD", "parameter", "polymorphism", "dictated", "dodged", "cats and dogs"};
int result = numberOfCharacters(strings, 'e');
System.out.println("No. of occurrences of 'e' is " + result);
}
public static String numberOfCharacters(String str, char a) {
int aresult = 0;
if (str.length() > 0) {
aresult = count(str.substring(1), a) + (str.charAt(0) == a ? 1 : 0);
}
return aresult;
}
}
Just change your method signature to:
public static String numberOfCharacters(String[] str, char a) {
///code
}
+1 for santosh's answer. I have tried it in following way . Try it out
public class CountChar {
public static void main(String[] args) {
String[] strings
= {"hidden", "Java SDK", "DDD", "parameter", "polymorphism",
"eeeee", "dodged", "cats and dogs"};
int result = 0;
for(int i=0;i<strings.length;i++) {
result += numberOfCharacters(strings[i], 'e');
}
System.out.println("No. of occurrences of 'e' in String is "+ result);
}
public static int numberOfCharacters(String str, char a) {
int counter = 0;
for( int i=0; i<str.length(); i++ ) {
if( str.charAt(i)== a ) {
counter++;
}
}
return counter;
}
}
In one liner:
Arrays.toString(strArray).replaceAll("[^"+a+"]", "").length();
Where 'a' is the char and 'strArray' the array of strings.
Using idea on how to count chars in a String from this question:
Java: How do I count the number of occurrences of a char in a String?
Complete code:
import java.util.Arrays;
public class CountChar {
public static void main(String[] args) {
String[] strings
= {"hidden", "Java SDK", "DDD", "parameter", "polymorphism",
"eeeee", "dodged", "cats and dogs"};
System.out.println("No. of occurrences of 'e' is " +
countCharsInArray(strings, 'e'));
}
public static int countCharsInArray(String strArray[], char a) {
return Arrays.toString(strArray).replaceAll("[^"+a+"]", "").length();
}
}
Explaining it:
'Arrays.toString(strArray)' converts the array into a single string.
'replaceAll("[^"+a+"]", "")' replace all characters that are not the one we want by empty char '',
After that we only need to check the length of the resulting string.
Note: The array should not have nulls, or they should be removed first.

How can I split a string into words in Java without using String.split()?

My teacher specifically requested that we split a sentence into words without using String.split(). I've done it using a Vector (which we haven't learned), a while-loop, and substrings. What are other ways of accomplishing this? (preferably without using Vectors/ArrayLists).
I believe that your teacher is asking you to process the string yourself (without using any other libraries to do it for you). Check to see if this is the case - if you can use them, there are things such as StringTokenizer, Pattern, and Scanner to facilitate string processing.
Otherwise...
You will need a list of word separators (such as space, tab, period, etc...) and then walk the array, building a string a character at a time until you hit the word separator. After finding a complete word (you have encountered a word separator character), save it the variable out into your structure (or whatever is required), reset the variable you are building the word in and continue.
Parsing the string character by character, copying each character into a new String, and stopping when you reach a white space character. Then start a new string and continue until you reach the end of the original string.
You can use java.util.StringTokenizer to split a text using desired delimiter. Default delimiter is SPACE/TAB/NEW_LINE.
String myTextToBeSplit = "This is the text to be split into words.";
StringTokenizer tokenizer = new StringTokenizer( myTextToBeSplit );
while ( tokinizer.hasMoreTokens()) {
String word = tokinizer.nextToken();
System.out.println( word ); // word you are looking in
}
As an alternate you can also use java.util.Scanner
Scanner s = new Scanner(myTextToBeSplit).useDelimiter("\\s");
while( s.hasNext() ) {
System.out.println(s.next());
}
s.close();
You can use java.util.Scanner.
import java.util.Arrays;
public class ReverseTheWords {
public static void main(String[] args) {
String s = "hello java how do you do";
System.out.println(Arrays.toString(ReverseTheWords.split(s)));
}
public static String[] split(String s) {
int count = 0;
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
count++;
}
}
String temp = "";
int k = 0;
String[] rev = new String[count + 1];
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
rev[k++] = temp;
temp = "";
} else
temp = temp + c[i];
}
rev[k] = temp;
return rev;
}
}
YOu can use StringTokenizer
http://www.java-samples.com/showtutorial.php?tutorialid=236
Or use a Pattern (also known as a regular expression) to try to match the words.
Use a Scanner with ctor (String)
regular expressions and match
StringTokenizer
iterating yourself char by char
recursive iteration
Without using a Vector/List (and without manually re-implementing their ability to re-size themselves for your function), you can take advantage of the simple observation that a string of length N cannot have more than (N+1)/2 words (in integer division). You can declare an array of strings of that size, populate it the same way you populated that Vector, and then copy the results to an array of the size of the number of words you found.
So:
String[] mySplit( String in ){
String[] bigArray = new String[ (in.length()+1)/2 ];
int numWords = 0;
// Populate bigArray with your while loop and keep
// track of the number of words
String[] result = new String[numWords];
// Copy results from bigArray to result
return result;
}
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class sha1 {
public static void main(String[] args) {
String s = "hello java how do you do";
System.out.println(Arrays.toString(sha1.split(s)));
}
public static String[] split(String s) {
int count = 0;
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
count++;
}
}
String temp = "";
int k = 0;
String[] rev = new String[count + 1];
for (int i = c.length-1; i >= 0; i--) {
if (c[i] == ' ') {
rev[k++] = temp;
temp = "";
} else
temp = temp + c[i];
}
rev[k] = temp;
return rev;
}
}
Simple touch.! Improve if you want to.
package com.asif.test;
public class SplitWithoutSplitMethod {
public static void main(String[] args) {
split('#',"asif#is#handsome");
}
static void split(char delimeter, String line){
String word = "";
String wordsArr[] = new String[3];
int k = 0;
for(int i = 0; i <line.length(); i++){
if(line.charAt(i) != delimeter){
word+= line.charAt(i);
}else{
wordsArr[k] = word;
word = "";
k++;
}
}
wordsArr[k] = word;
for(int j = 0; j <wordsArr.length; j++)
System.out.println(wordsArr[j]);
}
}
Please try this .
public static String[] mysplit(String mystring) {
String string=mystring+" "; //append " " bcz java string does not hava any ending character
int[] spacetracker=new int[string.length()];// to count no. of spaces in string
char[] array=new char[string.length()]; //store all non space character
String[] tokenArray=new String[string.length()];//to return token of words
int spaceIndex=0;
int parseIndex=0;
int arrayIndex=0;
int k=0;
while(parseIndex<string.length())
{
if(string.charAt(parseIndex)==' '||string.charAt(parseIndex)==' ')
{
spacetracker[spaceIndex]=parseIndex;
spaceIndex++;
parseIndex++;
}else
{
array[arrayIndex]=string.charAt(parseIndex);
arrayIndex++;
parseIndex++;
}
}
for(int i=0;i<spacetracker.length;i++)
{
String token="";
for(int j=k;j<(spacetracker[i])-i;j++)
{
token=token+array[j];
k++;
}
tokenArray[i]=token;
//System.out.println(token);
token="";
}
return tokenArray;
}
Hope this helps
import java.util.*;
class StringSplit {
public static void main(String[] args)
{
String s="splitting a string without using split()";
ArrayList<Integer> al=new ArrayList<Integer>(); //Instead you can also use a String
ArrayList<String> splitResult=new ArrayList<String>();
for(int i=0;i<s.length();i++)
if(s.charAt(i)==' ')
al.add(i);
al.add(0, 0);
al.add(al.size(),s.length());
String[] words=new String[al.size()];
for(int j=0;j<=words.length-2;j++)
splitResult.add(s.substring(al.get(j),al.get(j+1)).trim());
System.out.println(splitResult);
}
}
Time complexity: O(n)
You can use java Pattern to do it in easy way.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
You can also use String.substring or charAt[].

Categories