Break down a long string into smaller string of given length [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I am trying to break down a long given string into a smaller string of given length x, and it returns an array of these small strings. But I couldn't print out, it gives me error [Ljava.lang.String;#6d06d69c
Please take a look at my code and help me out if I am doing wrong. Thanks so much!
public static String[] splitByNumber(String str, int num) {
int inLength = str.length();
int arrayLength = inLength / num;
int left=inLength%num;
if(left>0){++arrayLength;}
String ar[] = new String[arrayLength];
String tempText=str;
for (int x = 0; x < arrayLength; ++x) {
if(tempText.length()>num){
ar[x]=tempText.substring(0, num);
tempText=tempText.substring(num);
}else{
ar[x]=tempText;
}
}
return ar;
}
public static void main(String[] args) {
String[] str = splitByNumber("This is a test", 4);
System.out.println(str);
}

You're printing the array itself. You want to print the elements.
String[] str = splitByNumber("This is a test", 4);
for (String s : str) {
System.out.println(s);
}

Related

Java--make changes on argument without returning a new variable [duplicate]

This question already has answers here:
Modify an array passed as a method-parameter
(4 answers)
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 3 years ago.
I am trying to reverse words in a String in Java. It is initialliy passed as a char array. The way I tried is to convert it into a String array, make the change, and convert it back to a char array. However, changes are not made to the original array that is passed in as an argument, even if I tried to refer the new array to the original one. How do I handle this situation when we have to make modifications to the argument without returning anything in the function? Thanks.
public static void main(String[] args) {
char[] s = new char[] {'t','h','e',' ','s','k','y',' ','i','s',' ','b','l','u','e'};
reverseWords(s);
System.out.println(s);
}
public static void reverseWords(char[] s) {
String str = new String(s);
String [] strArray = str.split(" ");
int n = strArray.length;
int begin;
int end;
int mid = (n-1)/2;
for (int i=0; i<=mid; i++) {
begin = i;
end = (n-1) -i;
String temp = strArray[begin];
strArray[begin] = strArray[end];
strArray[end] = temp;
}
String s_temp = Arrays.toString(strArray).replace("[", "").replace("]", "").replace(",", "");
s = s_temp.toCharArray();
System.out.println(s);
}
You can't do s = ....
But, you can insert the characters into the existing s array and the caller will see the changed values.
Replace this:
s = s_temp.toCharArray();
with:
for(int i = 0; i < s_temp.length(); i++) {
s[i] = s_temp.charAt(i);
}
or use System.arraycopy().

Array opposite string. Must use arrays [duplicate]

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 4 years ago.
How do i make an array with the opposite letters of the first array im making? For example if the string is "Hello", i want to use arrays to print out "olleH". When i try to return the variables it tells me "String index out of range: -1". Can anyone please tell me why? This is my code so far:
public class april{
public static void main(String [] args){
System.out.println("What do you want backwards?");
System.out.println("Your new word is " + reverse(IO.readString()));
}
public static String reverse(String original){
char [] letters = new char [original.length()];
char [] opp = new char [original.length()];
char c= 'a';
char d= 'a';
String word= " ";
String opposite= " ";
for (int x=0;x<original.length();x++){
c = original.charAt(x);
letters[x]= c;
if (x!=0){
d = original.charAt(-x-1);
opp[-x]=d;
}
else if (x==0){
d = original.charAt(-1);
opp[x]= d;
}
word += letters[x];
opposite += opp[x];
}
return word;
return opposite;
You're close! You just need to start at the other end of the String for the second array (with proper syntax):
for (int x = 0; x < original.length(); x++) {
char c = original.charAt(x);
char d = original.charAt(original.length() - x - 1);
letters[x] = c;
opp[original.length() - x - 1] = d;
}
Note: You also have to subtract 1 because both arrays and string indices are 0-indexed.
I think this is a great way to do it.
public class Main {
public static void main(String[] args) {
String reversed = reverse("Hello");
System.out.println(reversed);
}
private static String reverse(String word) {
byte[] array = word.getBytes();
int i = 0;
int j = array.length - 1;
byte tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
return new String(array);
}
}
Your method receives a String and returns another String, so you don't need to work with arrays at all, just use the reverse method of the StringBuilder class.
public static String reverse(String original) {
return new StringBuilder(original).reverse().toString();
}

Unexpected output while splitting and parsing a string into int (Java) [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 5 years ago.
public static void main (String args[]) {
Scanner io = new Scanner(System.in);
int a = io.nextInt();
io.nextLine();
for(int i = 0; i < a; i++ ) {
String input = io.nextLine();
String[] splitArr = input.split("\\s+");
int p[] = new int[input.length()];
int q = 0;
for (String par : splitArr) {
System.out.println(par);
p[q++] = Integer.parseInt(par);
System.out.println(p);
}
Sort(p);
}
}
The input: 2 121213
Output: 121213 [I#1f96302
The last line shows the array stored in p[]. That is incorrect. Help someone!
Your print line is incorrect, your print line should be:
System.out.println(Arrays.toString(p));
You also increment q in a wrong way, your increment code should be like:
p[q] = Integer.parseInt(par);
q++;
System.out.println(p);

Split a String into Pieces [duplicate]

This question already has answers here:
Split string to equal length substrings in Java
(23 answers)
Closed 6 years ago.
I'm trying to split a string into different parts each having x amount of characters in it. How can I go along doing this?
EDIT: I've managed to figure itout thanks to #amith down below however I'm unsure how to make it not split words, any ideas?
Thanks,
- Exporting.
List<String> splitString(int interval, String str) {
int length = str.length();
List<String> split = new ArrayList<>();
if(length < interval) {
split.add(str);
} else {
for(int i=0;i<length;i+=interval) {
int endIndex = i + interval;
if(endIndex > length) {
endIndex = length;
}
String substring = str.substring(i, endIndex);
split.add(substring);
}
}
return split;
}
This is a sample code to split string at regular intervals
If result is an array of char, try this:
public static char[] split(String str, int numChar) {
char[] s = str.toCharArray();
if (numChar >= str.length()) {
return s;
}
char[] r = new char[numChar];
System.arraycopy(s, 0, r, 0, numChar);
return r;
}
Or if result is a String, try this:
public static String split(String str, int numChar) {
char[] s = str.toCharArray();
if (numChar >= str.length()) {
return String.copyValueOf(s);
}
char[] r = new char[numChar];
System.arraycopy(s, 0, r, 0, numChar);
return String.copyValueOf(r);
}
Please note that two of above methods do not change the original String.

how to reverse an inputted number [duplicate]

This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 8 years ago.
I want to reverse an inputted number. I've written the code for it. But i need to know if it could have been done in any other much faster way. Please feel free to modify my code.
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number");
int num=Integer.parseInt(in.readLine());
int no=num;
int d;
int rev_no=0;
int digits=0;
while(num>0)
{
num/=10;
digits++;
}
while(no>0)
{
d=no%10;
rev_no+=d*(Math.pow(10,(digits-1)));
no/=10;
digits--;
}
System.out.println(rev_no);
}
As #Christian mentioned above in the comments, you can do something like this:
int originalInt = 123456789;
String str = new StringBuilder(Integer.toString(originalInt)).reverse().toString();
int reversedInt = Integer.parseInt(str);
Or as a one-liner:
Integer.parseInt(new StringBuilder(Integer.toString(new Integer(123456789))).reverse().toString());
EDIT:
To answer #Luiggi Mendoza's concern - supporting numbers that are too big to fit an Integer can be done using BigInteger as follows:
BigInteger originalValue = BigInteger.valueOf(563463346233535772l);
String reversedString = new StringBuilder(originalValue.toString()).reverse().toString();
String myNum=num.toString();
String reversed = new StringBuffer(myNum).reverse().toString();
num=Integer.parseInt(reversed);
Example without StringBuilder.
private static long revert(long number){
String numberAsString = String.valueOf(number);
String[] splitted = numberAsString.split("");
String returnString = "";
for(int i = splitted.length-1; i >=0; i--){
returnString += splitted[i];
}
return Integer.valueOf(returnString);
}

Categories