java split unknown length of string in every 3 parts - java

public static void main(String[] args) {
String brandmodel="VolkswagenGolf";
String [] splitedstring=new String[13]
//how to insert every 3 letters in splitedstring array
}
What i want is to split the above string in every 3 letters.
For example
i want to save from the above string the next
Vol,ksw,age,nGo,lf
i have read here some crazy codes but i did not understand them,i want the simplest way.
I have not learned Regex yet

Calculate the number of parts you will have and create an array:
int parts = (string.length() + 2) / 3;
String splitted[] = new String[parts];
Fill the array, using String.substring(int, int):
for (int i = 0; i < parts; ++i)
{
int x = i * 3;
splitted[i] = string.substring(x, Math.min(string.length(), x + 3));
}
Substring takes a string out of another string, using indices.
The problem is that if you take a range that goes out of the string, an exception will be thrown. So what I do, is limiting the endIndex to the string length, by using Math.min(int, int). It will always return the smallest of the two passed values.
Example of this going wrong, without Math.min():
String str = "test";
String substr = str.substring(2, 9);
This fails (Exception) because, 9 is out of the range of str. str is only 4 characters long. So, valid startIndices are: {0, 1, 2, 3} and valid endIndices are in this case: {0, 1, 2, 3, 4}.

You could use regex look-behind matching the last match plus any 3 characters:
String[] splitString = brandmodel.split("(?<=\\G...)");
The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))
Output:
[Vol, ksw, age, nGo, lf]

There's no "crazy code" required, it's a relatively straightforward:
String[] res = new String[(s.length()+2)/3];
for (int i = 0 ; i != res.length ; i++) {
res[i] = s.substring(3*i, Math.min(3*i+3, s.length()));
}
On ideone: link.

It works for all length of String
String brandmodel="VolkswagenGolf";
List <String> splitedstring = new ArrayList<String>();
int i = 0;
while(brandmodel.length() > 2 )
{
splitedstring.add(brandmodel.substring(0,3));
brandmodel = brandmodel.substring(3);
}
if(brandmodel.length() > 0)
splitedstring.add(brandmodel);

Related

Replace "*" with "-" in given character array

Given character array is
char[] arr = {123*4*5}
output should be
String str = "123-4-5"
1) That's not how you declare a char array. As pointed in comments it should be:
char[] arr = {'1','2','3','*','4','*','5'};
2) If you want a String why don't you start with a String?
3) You could construct a String from a char[] and use String.replace(char oldchar, char new char) which comes as the first result in a Google search. Code:
char[] arr = {'1','2','3','*','4','*','5'};
String str = String.valueOf(arr).replace('*', '-');
4) If you need to do it on a char[] before a String is made, you could simply loop through the array:
char[] arr = {'1','2','3','*','4','*','5'};
for(int i=0; i<arr.length; i++)
if(arr[i] =='*') arr[i] = '-';
String str = String.valueOf(arr);
EDIT: based on the comments and discussion with OP, the question seems to be exactly as posted. That is:
char[] arr = {xxx*y*z};
String str = transformCharArr(arr);
For arr={123*4*5}: str = "123-4-5" and for arr={122*2}: str = "122-2".
Therefore, I made a small function that achieves just that and solves both cases.
Assumptions:
1) xxx is always a three digit number, minimum is 100, maximum is 999.
2) y is non-zero 1 digit number [1-9], same with z.
3) In case y or z is equal to 1, it's ignored given multiplication by 1 changes nothing to the outcome.
4) xxx is always minimized. That is, for 123*4*5, the lowest possible xxx to achieve this is 123 with respect to assumption (1) that xxx>=100.
5) y and z are maximized with z being favored for maximization. Also with respect to assumption (2) for both.
Therefore, code is:
static String transformCharArr(char[] arr){
if(arr.length > 1) return ""; // array should only contain 1 element
int value = (int)arr[0]; // using int since char is the only unisgned 2-byte type in all of Java, short isn't enough given MAX(short) = 32,767 while max(char) = 65,535
short xxx=100, y=1, z=1; // all shorts since they never exceed certain limits
int product = 0; // to stop the loop, int because short*short*short gives int type, and product is comparable to value, so it has to support more than max(short)
for(xxx=100; xxx<=999; xxx++){ // first loop xxx to minimize it
for(y=1; y<=9; y++){ // loop y before z to favor maximizing z
for(z=1; z<=9; z++){ // ensures maximizing z before y
if((product = xxx*y*z)== value)
break;
}
if(product == value) break;
}
if(product == value) break;
}
if(y==1) return String.format("%d-%d", xxx, z); // if y is 1, ignore it
if(z==1) return String.format("%d-%d", xxx, y); // if z is 1 ignore it
return String.format("%d-%d-%d", xxx,y,z);
}
Testing it:
public static void main(String[] args) {
char[] arr1 = {123*4*5};
System.out.println(transformCharArr(arr1));
char[] arr2 = {122*2};
System.out.println(transformCharArr(arr2));
}
Output:
123-4-5
122-2
Analysis:
Time-complexity: O(C) given the loop cannot run more than 999*9*9 and it is ALWAYS guaranteed to find value before xxx=9 y=9 z=9 given that 999*9*9 = ‭80,919‬ > max(char)=65,535
The first thing you should know is that the 123 * 4 * 5 means 2460,so the point by upstairs is right.which like this :
char[] arr = {'1','2','3','*','4','*','5'};
System.out.println(new String(arr).replaceAll("\\*","-"));
char[] arr = {'1','2','3','*','4','*','5'};
String str = String.valueOf(arr).replace('*', '-');
get a string from your char arrays and take the replace method to repalce '*' from '-'

How to form a vertical string pattern using an integer array for spacing count?

Let me explain. Say I have a given array of integers:
public static void spacing(String str)
int[] spacing = new int[]{1, 2, 3, 2, 1};
//Some function to find the given number in
//the array and coverts to the equal number of spaces
for (int i = 0; i < str.length(); i++)
System.out.println((the method for spacing) + str.charAt(i));
public static void main(String[] args)
spacing("Wow!!");
I understand it is not formatted properly. I just copied the gist over so you can get an idea of what I am wondering. How can I convert those given integers into the same number of spaces?
(Meaning 1 would print 1 space, 2 would print 2 spaces, 3 spaces, etc...)
Is it possible to print the space character spacing[i] times?
Edited: I am limited to only importing java.utils.Arrays java.lang I have also updated the text to show how it needs to produce a pattern. I have also tried some of the answer provided, however it is still not printing the correct number of spaces.
I have tried converting the int array to a char array and using Array.fill and while it fills the array with spaces, it's only one space per array value (instead of 2 having 2 spaces, it puts 1 space for each value). My program is supposed to take characters from the user (which it already does) I am just having trouble getting the array to print the proper number of spaces before each character.
This is how the expected result looks if the user enters "Wow!!":
W
o
w
!
!
You can do something like this:
public static void main(String[] args)
{
String space = " ";
int[] spacing = new int[]{1, 2, 3, 4, 5};
for (int n: spacing) {
System.out.print(String.join("", Collections.nCopies(n, space)));
System.out.println("End of line");
}
}
I've added the "End of line" just for example purposes
You can create a method and pass integer as argument. append string with spaces and loop it based on passed integer and return string of spaces like this
public static void main(String args[]) {
String str = "Wow!!";
int[] spacing = new int[]{1, 2, 3, 2, 1};
for (int i = 0; i < str.length(); i++) {
System.out.println(method2(i) + str.charAt(i));
}
}
static String method2(int n) {
String space = "";
for (int i = 1; i <= n; i++) {
space = space + " ";
}
return space;
}
call this method before printing number or character it.

Java - Large String need to split with different field length

I'm new to Java and didn't find any exact solution for my scenario. I have a large string which is 1500 length.
For example :
String inData = "THISKALJSKAJFDSKJDKSJ KSJDLKJSFKD LSKJDFKSJ, ASA:..";
I have a fixed format for these 1500 length. I have to split the string into 200+ fields based on each field fixed length. I found something like below.
String firstFld = inData.substring(0, 2);
String secondFld = inData.substring(3, 10);
String thirdFld = inData.substring(11, 13);
can anyone please suggest with better way of doing the split instead of declaring 200 string variables and store them there or loading them to a String Array ? I plan to to build an xml with all these fields after getting them.
I appreciate all your help!
Well, if it's two of the below, then this would work:
There's a pattern for the field lengths: like (0,2), (3, 10), (11,13), (14, 21) ...
You have a list of field lengths
In both cases it is pretty simple to solve what you want:
First Case: Pattern is 2 chars -> 7 chars starting with 2
String[] fields = new String[getNumberOfFields(1500)];
int curr = 0;
for(int i = 0 ; i < fields.length; i++) {
if(i % 2 == 0) {
fields[i] = inData.substring(curr, curr+7);
curr+=8;
} else {
fields[i] = inData.substring(curr, curr+2);
curr+=3;
}
}
Second Case: You have a bunch of different field lenghts
int curr = 0;
String[] fields = new String[fieldLengths.length];
for(int i = 0; i < fieldLengths.length; i++) {
fields[i] = inData.substring(curr, curr+fieldLengths[i]);
}

calculating the number of string occurances in another string

This is my assignment. I am not allowed to use if statements.
Write a program NumStrings.java that receives two strings through the command line as
input and then prints out the number of times the second string occurs as a substring in the
first.
My bad code:
public class Test {
public static void main(String[] args) {
String a = "HelloHelloHelloHello";
String b = "Hello";
int times = 0;
for(int i=0; i <= a.length()-5; i++){
for (int z=4; z<=(a.length()-1) && a.compareTo(b)==0; z++){
times = times +1;
}
}
System.out.print(times);
}
}
Here is the correct way to do it, using subString() (documentation here: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)):
String a = "HelloHelloHelloHello";
String b = "Hello";
int times = 0;
for (int i = 0; i <= a.length() - b.length(); i++) {
String substring = a.subString(i, i + b.length());
if (substring.equals(b)) {
times = times + 1;
}
}
System.out.println(times);
And here is a way to do it without if statements... Which I don't recommend. But if you have to do it that way, this will work.
String a = "HelloHelloHelloHello";
String b = "Hello";
int times = 0;
for (int i = 0; i <= a.length() - b.length(); i++) {
String substring = a.substring(i, i + b.length());
for (int j = 0; substring.equals(b) && j < 1; j++) {
times = times + 1;
}
}
System.out.println(times);
Look at it this way: you don't have to count how often you find the second string in the first String, because you always have to check if you found it or not. So, to avoid all sorts of conditions or if statements, consider using firstString.split(secondString).
split(someString) will return you an array of remaining substrings once you "split" the base string everytime it finds your substring:
String first = "bababa";
String second = "a";
String[] substrings = first.split(second);
now substrings will look like this: ["b", "b", b"] because every a has been removed and the rest put in separate Strings.
Next you have to check the size of the array and you'll see how often your first String was split.
int count = substrings.length; // 3
However, this is not the end of it because we still have the following case:
String first = "bababaa";
With the above solution you would get an array of size 3: ["b", "b", "b"]. The last occurrence of a will only be removed without leaving any substring behind (not even an empty one '').
So you can take advantage of another (slightly different) split():
first.split(second, limit);
Where limit is the maximum number of occurrences the method tries to find. So how often can you find your second string in the first one? As many letters the first string has: int limit = first.length
first.split(second, first.length); // will produce [b, b, b, , ]
Can you see what happens? there are two empty strings at the end where there where two a. You get an array of substrings for everything that is found before or after the occurrence of the second String.
Naturally, when you split the string ba you would get ["b", ] so 2 substrings. But you don't care about the b just the "commas" in the middle (for every a a ,).
first.split(second, first.length).length -1; // that's how many commas there are, and thats how many second strings there are
EDIT
(thanks #saka1029 !) So, the "split" method still misses something when first="aaa" and second="aa" because it counts only 1 not 2 occurrences.
To correct that I thought of looping through the whole first string and checking only for the very first occurrence, and then removing the first letter and continuing (since OP already accepted another answer, I just post my code):
String first = "ZZZ";
String second = "ZZ";
int counter = 0; // counts the number of occurrences
int n = first.length(); // needs to be fixed, because we'll change the length of the first string in the loop
for(int i = 0; i < n; i++){ // check the first string letter by letter
String[] split = first.split(second, 2); // we want one substring and the rest (2 in total) like: ['', 'Z'] when we cut off the first 'ZZ'
counter += split.length - 1; // now add the number of occurrences (which will be either 0 or 1 in our case)
first = first.substring(1); // cut off the first letter of the first string and continue
}
System.out.println("counter = " + counter); // now we should get 3 for 'ZZZ'

Java - Split a string to an array

I have a number that is submitted by the user.
I want to make something like this: 1568301
to an array like this: 1, 5, 6, 8, 3, 0, 1.
How can I do this without adding "," between every digit or something like that? (type int).
Thanks.
String str = "123456";
str.toCharArray();
will do roughly what you want. A more complex version using a regular expression is:
String str = "123456";
str.split("(?<!^)");
which uses a negative lookbehind (split() takes a regexp - the above says split on anything provided the element to the left isn't the start-of-line. split("") would give you a leading blank string).
The second solution is more complex but gives you an array of Strings. Note also that it'll give you a one-element empty array for a blank input. The first solution gives you an array of Chars. Either way you'll have to map these to Integers (perhaps using Integer.parseInt() or Character.digit()?)
"1568301".toCharArray() should do the job.
You can use the Split with ""
It'll be like this:
String test = "123456";
String test2[] = test.split("");
for (int i = 1; i < test2.length; i++) {
System.out.println(test2[i]);
}
If your number is in String format, you can simply do this:
String str = "1568301";
char[] digitChars = str.toCharArray();
Are expecting something like this
String ss ="1568301";
char[] chars = ss.toCharArray();
cant you simply populate the array by iterating over the String ??
char[] arr = new char[str.length];
for(int i=0; i<str.length; i++){
arr[i] = str.charAt(i);
}
or even better
char[] arr = "0123456".toCharArray();
To get the values in an array of integers:
String str = "1568301";
int[] vals = new int[str.length];
for (int i = 0; i < str.length(); i++) {
vals[i] = Character.digit(str.charAt(i), /* base */ 10));
}
The second parameter of Character.digit(char, int) is the number base. I'm assuming your number is base 10.
I guess you are looking at to have an array of int.
I would suggest to have the following code :
String str = "1568301";
int [] arr = new int[str.length()];
for(int i=0; i<arr.length; i++)
{
arr[i] = str.charAt(i)-'0';
}

Categories