Suppose I have a string array as follows:
String[] str = {"2","4","5"};
Now I want to subtract 1 from each of its elements, ie, I want the string to be like this now:
str = {"1","3","4"};
How do I do it? Is there any way other than converting it into an integer array?
Try this,
String str[]= {"2","4","5"};
for(int i=0;i<str.length;i++)
{
str[i]=String.valueOf(Integer.parseInt(str[i])-1));
}
You have to convert them into integers, but not necessarily store into an array of integers. You can do the math in-place instead:
for(int i = 0; i < str.length; i++) {
str[i] = Integer.toString(Integer.parseInt(str[i]) - 1);
}
However, this is a code smell to me. Strings do not tend to be the best choice when doing math in general. You might also want to work with an int[] internally and convert them to strings when needed.
You would need to convert them to Integers.
If you could make some crazy constraints, you could get it a little better, for example...
Only having single digit integers in an array of characters, strictly greater than zero. You could then do the "math" by subtracting 1 from their ASCII value, but this is a pretty crazy situation to even ever have.
convert string to int : int foo = Integer.parseInt("1234");
Subtract 1 from it
Convert back to string Integer.toString(i)
That makes
for (int i = 0; i < strn.length; i++)
strn[i] := String.valueOf(Integer.parseInt(strn[i]) - 1);
}
for (int i = 0; i < str.length; i++)
str[i] := String.valueOf(Integer.parseInt(str[i]) - 1);
}
Hope this will helps you.
public String[] stringCal(String[] ele,int numbr){
String[] sCalulated = new String[ele.length];
for(int i = 0; i < ele.length ; i ++){
sCalulated[i] = String.valueOf(Integer.parseInt(ele[i])-numbr);
}
return sCalulated;
}
public static void main(String[] args) throws IOException {
String str[] = subtractOn(new String[]{"2","4","5"});
for(int k=0;k<str.length;k++){
System.out.println("Integer is :" +str[k]);
}
}
public static String[] subtractOn(String str[]){
int intArray[] = new int[str.length];
String stres[] = new String[str.length];
for(int i=0;i<str.length;i++){
intArray[i] = Integer.parseInt(str[i]);
}
for(int j=0;j<intArray.length;j++){
stres[j] = String.valueOf(intArray[j]-1);
}
return stres;
}
You can use org.apache.commons.lang3.math library to solve it in an elegant way.
for(int i = 0; i < str.length; i++) {
str[i] = NumberUtils.toInt(str[i]) - 1;
}
Related
I have a function to get a a string as a repetition of an original string. I'm wondering if I use StringBuilder append, what is the Big O of the function? Is it O(nl) : n is number of repeats and l is length of the original string ?
public String getRepetition(String originalStr, Integer n){
StringBuilder str = new StringBuilder();
for(int i = 0; i < n; i++)
str.append(originalStr);
return str.toString();
}
Comparing with the approach below, which one is better?
public String getRepetition(String originalStr, Integer n){
String str = "";
for(int i = 0; i < n; i++)
str += originalStr;
return originalStr;
}
I'm not sure why other three answers are all saying both pieces of code are O(n). Assuming originalStr is not "", the first is O(n) the other O(n^2)! (That's an exclamation, not a factorial.) They teach this on the first day of Java school. C programmers get "don't use strlen in the condition of that for loop"; Java programmers get this.
String str = "";
for(int i = 0; i < n; i++)
str += originalStr;
Each time around this loop str is getting longer. It's i * orginalStr.length(). Creating a new String (assuming no wild compiler optimisations) which takes time roughly proportional to i each time.
Edit: Usually we ignore the length of the original string. But yeah, of course it's going to be proprotional, so O(nstrlen(originalStr)) and O(nn*strlen(originalStr)). By convention this is dealt with separately.
If we rewrite the code without the String abstraction, perhaps it will be clearer.
public static char[] getRepetition(char[] originalStr, int n) {
char[] str = {};
for (int i = 0; i < n; ++i) {
assert str.length == i * originalStr.length;
char[] newStr = new char[str.length + originalStr.length];
for (int j=0; j<str.length; ++j) {
newStr[j] = str[j];
}
for (int j=0; j<originalStr.length; ++j) {
newStr[str.length+j] = originalStr[j];
}
str = newStr;
}
return str;
}
(As ever, I've not bothered to so much as compile the code. Not safe to use in a nuclear reactor.)
Just for giggles, let's deabstract the first implementation.
public static char[] getRepetition(char[] originalStr, int n) {
char[] str = new char[16];
int strLen = 0;
for (int i = 0; i < n; ++i) {
assert strLen == i * originalStr.length;
// ensureCapacity
if (str.length < strLen + originalStr.length) {
// The size at least doubles,
// so this happens increasing less often.
// It wont happen again for approximately
// the same number of iterations
// as have already happened!
char[] newStr = new char[Math.min(
str.length + originalStr.length, // first time safe
str.length*2 + 2 // *2 !
)];
for (int j=0; j<strLen; ++j) {
newStr[j] = str[j];
}
str = newStr;
}
// actual append
for (int j=0; j<originalStr.length; ++j) {
str[strLen++] = originalStr[j];
}
}
// toString
char[] newStr = new char[strLen];
for (int i=0; j<newStr.length; ++i) {
newStr[i] = str[j];
}
return newStr;
}
Both of your approaches are O(n) while the first approach eliminates several temporary String(s). It isn't clear why you have made n an Integer, nor why you have not made this a static method (it depends on no instance state). Additionally, in Java 8+, you could implement it with a lambda like
public static String getRepetition(String originalStr, int n) {
return Stream.generate(() -> originalStr).limit(n).collect(Collectors.joining());
}
Also, if you're going to use a StringBuilder as in your first example, you can explicitly size it to avoid having to amortize the cost of resizing the StringBuilder
StringBuilder str = new StringBuilder(originalStr.length() * n);
In both the cases the complexity is O(n) because you are iterating n times.
The only difference in second approach is you are creating new String in each iteration i.e. at str += originalStr;
This is my code, but I know this is not right. I have written a lot of code for such a simple task.
Sample input is:
welcome
Sample output is:
com
elc
lco
ome
wel
It should print:
your first string is 'com'
and
your last string is 'wel'
Code:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int k = sc.nextInt();
int k1 = k;
int j = 0;
int t = str.length();
String [] s = new String [1000];
for (int i = t, a = 0; i >= k; i--, a++) {
s[a] = str.substring(j, k1);
j++;
k1++;
}
String[] s1 = new String[j];
for (int i = 0 ; i < j; i++) {
s1[i] = s[i];
}
for (int y = 0; y < j; y++) {
for (int z = y + 1; z < j; z++) {
if(s1[z].compareTo(s1[y]) < 0) {
String temp = s1[z];
s1[z] = s1[y];
s1[y] = temp;
}
}
}
System.out.println(s1[0]);
System.out.println(s1[1]);
}
}
Note: I split my strings, but I'm not able to arrange strings in alphabetical order, and feel that I have used a lot of arrays. Is there a better way to do this?
You can
reduce the number of variables,
use collections (list in this case) instead of Arrays to avoid having to set a size (1000)
Sort using the framework
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int k = sc.nextInt();
List<String> cutStrings = new ArrayList<String>();
for (int i = 0; i < str.length() - k; i++) {
cutStrings.add(str.substring(i, i + k));
}
Collections.sort(cutStrings);
System.out.println(cutStrings.get(0));
System.out.println(cutStrings.get(cutStrings.size()-1));
}
You can easily sort your String[] array by simply using
Arrays.sort(s);
This will sort your strings in the default order. If you need any other kind of order you can pass the comparator as a second parameter.
You can get first and last by getting s[0] and s[s.length-1]
I did a quick implementation of your requirements. It might not be exactly what you're looking for but it should get you started. :)
So, I used an ArrayList to grab the substrings and the use the Collections library to do the sorting for me. This is just one of the many ways of solving the problem, btw. The input word can vary in size so I felt that a list would be appropriate for this situation.
String s = "welcome";
List<String> words = new ArrayList<String>();
for (int i = 0; i < s.length() - 2; i++) {
String chunk = s.charAt(i) + "" + s.charAt(i + 1) + ""
+ s.charAt(i + 2);
words.add(chunk);
System.out.println(chunk);
}
Collections.sort(words);
System.out.println(words.toString());
Feel free to let me know if you have any questions or if I have made a mistake in the code.
Good luck!
Actual problem of your code is splitting. Sorting will work. If j value 1 and k1 value 3 then wel substring is coming. Next loop, (after incrementation of both j and k1 by 1) j value 2 and k1 value 4 then elc substring is coming, etc.
So, instead of
String [] s = new String [1000];
for (int i = t, a = 0; i >= k; i--, a++) {
s[a] = str.substring(j, k1);
j++;
k1++;
}
use
int k = sc.nextInt();
String [] s = new String [(str.length()/3)+1] ;
for ( int i = 0,a = 0; i<(str.length()-k); i+=k,a++)
{
s[a] = str.substring(i,(i+k));
System.out.println(s[a]);
}
s[s.length-1]=str.substring((str.length()-k),str.length());//to add remaining values
Arrays.sort(s);//sorting alphabatically
for(int i = 0; i < s.length; i++)
System.out.println(s[i]);
}
i value will be incremented by 3. In the for loop (i+=k) where k=3.
Output:
amp
com
e s
ple
wel
How is it possible in java to have an int array and add all values from the array to a numerical series.
For example:
int[] num= new int[9];
for(int i=0; i<num.length; i++) {
num[i] = i;
}
and I need one integer variable like:
int a = 12345678910
copied from the array.
thx a lot in advance!
There are 2 problems in your code which you'll need to fix first:
your array index is bigger than the size of the array (11 > 9)
the number you're assigning to 'a' is too big for the integer type
You could try this as a solution:
StringBuilder numbers = new StringBuilder();
int[] num = new int[9];
for (int i = 0; i < num.length; i++) {
num[i] = i;
numbers.append(i);
}
long a = Long.valueOf(numbers.toString());
System.out.println(a);
Note that you'll still need to check that the final output of 'numbers' is not too big for a long. If it is you'll need to use a data type that can accommodate the resulting value.
It seems most natural to use the StringBuilder class, as this handles your appending 2 digit numbers most easily:
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 11; i++) {
sb.append(i);
}
int a = Integer.parseInt(sb.toString());
int a;
String aStr = "";
int[] num= new int[9];
for(int i=0; i<11; i++) {
aStr = aStr + num[i];
}
a = new Integer(aStr);
I have problem with conversion from String into two dimension int array.
Let's say I have:
String x = "1,2,3;4,5,6;7,8,9"
(In my program it will be String from text area.) and I want to create array n x n
int[3][3] y = {{1,2,3},{4,5,6},{7,8,9}}
(Necessary for next stages.) I try to split the string and create 1 dimensional array, but I don't have any good idea what to do next.
As you suggest I try split at first using ; then , but my solution isn’t great. It works only when there will be 3 x 3 table. How to create a loop making String arrays?
public int[][] RunMSTFromTextFile(JTextArea ta)
{
String p = ta.getText();
String[] tp = p.split(";");
String tpA[] = tp[0].split(",");
String tpB[] = tp[1].split(",");
String tpC[] = tp[2].split(",");
String tpD[][] = {tpA, tpB, tpC};
int matrix[][] = new int[tpD.length][tpD.length];
for(int i=0;i<tpD.length;i++)
{
for(int j=0;j<tpD.length;j++)
{
matrix[i][j] = Integer.parseInt(tpD[i][j]);
}
}
return matrix;
}
After using split, take a look at Integer.parseInt() to get the numbers out.
String lines[] = input.split(";");
int width = lines.length;
String cells[] = lines[0].split(",");
int height = cells.length;
int output[][] = new int[width][height];
for (int i=0; i<width; i++) {
String cells[] = lines[i].split(",");
for(int j=0; j<height; j++) {
output[i][j] = Integer.parseInt(cells[j]);
}
}
Then you need to decide what to do with NumberFormatExceptions
Split by ; to get rows.
Loop them, incrementing a counter (e.g. x)
Split by , to get values of each row.
Loop those values, incrementing a counter (e.g. y)
Parse each value (e.g. using one of the parseInt methods of Integer) and add it to the x,y of the array.
If you have already created an int[9] and want to split it into int[3][3]:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
toArray[i][j] = fromArray[(3*i) + j);
}
}
Now, if the 2-dimensional array is not rectangular, i.e. the size of inner array is not same for all outer arrays, then you need more work. You would do best to use a Scanner and switch between nextString and next. The biggest challenge will be that you will not know the number of elements (columns) in each row until you reach the row-terminating semi-colon
A solution using 2 splits:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
String[][] result = new String[x.length][];
for (int i = 0; i<x.length; i++) {
result[i] = x[i].split(",");
}
This give a 2 dimension array of strings you will need to parse those ints afterwards, it depends on the use you want for those numbers. The following solution shows how to parse them as you build the result:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
int[][] result = new int[x.length][];
for (int i = 0; i < x.length; i++) {
String[] row = x[i].split(",");
result[i] = new int[row.length];
for(int j=0; j < row.length; j++) {
result[i][j] = Integer.parseInt(row[j]);
}
}
Super simple method!!!
package ADVANCED;
import java.util.Arrays;
import java.util.Scanner;
public class p9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String x=sc.nextLine();
String[] array = x.split(",");
int length_x=array.length;
int[][] two=new int[length_x/2][2];
for (int i = 0; i <= length_x-1; i=i+2) {
two[i/2][0] = Integer.parseInt(array[i]);
}
for (int i = 1; i <= length_x-1; i=i+2) {
two[i/2][1] = Integer.parseInt(array[i]);
}
}
}
How can I convert the ints in a 2d array into chars, and strings? (seperately)
If I copy ints to a char array i just get the ASCII code.
For example:
public int a[5][5]
//some code
public String b[5][5] = public int a[5][5]
Thanks
This question is not very well-phrased at all. I THINK what you're asking is how to convert a two-level array of type int[][] to one of type String[][].
Quite frankly, the easiest approach would simply leave your array as-is... and convert int values to String's when you use them:
Integer.toString(a[5][5]);
Alternatively, you could start with a String[][] array in the first place, and simply convert your int values to String when adding them:
a[5][5] = new String(myInt);
If you really do need to convert an array of type int[][] to one of type String[][], you would have to do so manually with a two-layer for() loop:
String[][] converted = new String[a.length][];
for(int index = 0; index < a.length; index++) {
converted[index] = new String[a[index].length];
for(int subIndex = 0; subIndex < a[index].length; subIndex++){
converted[index][subIndex] = Integer.toString(a[index][subIndex]);
}
}
All three of these approaches would work equally well for conversion to type char rather than String.
Your code must basically go through your array and transform each int value into a String. You can do this with the String.toString(int) method.
You can try that :
String[][] stringArray = new String[a.length][];
for(int i = 0; i < a.length; i++){
stringArray[i] = new String[a[i].lenght];
for(int j = 0; j < a[i].length; j++){
stringArray[i][j] = Integer.toString(a[i][j]);
}
}
If you want the int number as a string then you can use the Integer.toString() function.
b[1][1] = Integer.toString(a[1][1]);
String [][]b = new String[a.length][];
for(int i=0; i<a.length; i++) {
int [] row = a[i];
b[i] = new String[row.length];
for(int j=0; j<row.length; j++) {
b[i][j] = Integer.toString(row[j]);
}
}
To convert a 2D array into String you can use Arrays.deepToString(stringArr).