Separating a String to an Array [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How can i seperate this String:
"thisisanexampleforthisproblemicantsolvetestes"
To this array:
{"thisi","sanex","ampl","efor","this","prob","lemi","cant","solv","etes","tes"}
I want to seperate the first 10 letters in the String into 2 elemnts in an array and the rest should be every 4 letters, to one elemnt in an array.
I hope you can help me. I tried this all day but still didnt solve it

Assuming your input string length >= 10 you can do something like below using streams:
String str = "thisisanexampleforthisproblemicantsolvetestes";
String[] splited = Stream.of(str.substring(0, 10).split("(?<=\\G.{5})"),
str.substring(10).split("(?<=\\G.{4})"))
.flatMap(e -> Arrays.stream(e))
.toArray(String[]::new);
System.out.println(Arrays.toString(splited));
where the regex "(?<=\\G.{n})" is used to split a string at each nth char

More simple to understand:
Results in: thisi, sanex, ampl, efor, this, prob, lemi, cant, solv, etes, tes
public static List<String> strangeThingsDo(String str)
{
List<String> li = new ArrayList<>();
int len = str.length();
if (len <= 5)
{
li.add(str);
return li;
}
if (len <= 10)
{
li.add(str.substring(0,5));
li.add(str.substring(5));
return li;
}
li.add(str.substring(0,5));
li.add(str.substring(5,10));
String s,rest = str.substring(10);
int restlen = rest.length();
int end = 0;
for (int i = 0; i < restlen;i += 4)
{
end = i + 4;
if (end > restlen)
{ s = rest.substring(i);
li.add(s);
break;
}
s = rest.substring(i,end);
li.add(s);
}
System.out.println("---: " + li );
return li;
}

The following code will show you how to split a string by numbers of characters. We create a method called splitToNChars() that takes two arguments. The first arguments is the string to be split and the second arguments is the split size.
This splitToNChars() method will split the string in a for loop. First we’ll create a List object that will store parts of the split string. Next we do a loop and get the substring for the defined size from the text and store it into the List. After the entire string is read we convert the List object into an array of String by using the List‘s toArray() method.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SplitStringForEveryNChar {
public static void main(String[] args) {
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(Arrays.toString(splitToNChar(text, 3)));
System.out.println(Arrays.toString(splitToNChar(text, 4)));
System.out.println(Arrays.toString(splitToNChar(text, 5)));
}
private static String[] splitToNChar(String text, int size) {
List<String> parts = new ArrayList<>();
int length = text.length();
for (int i = 0; i < length; i += size) {
parts.add(text.substring(i, Math.min(length, i + size)));
}
return parts.toArray(new String[0]);
}
}

Related

Recursively computing all possible permutations of a string Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to compute all possible permutations of a given string using recursion in Java. However, I don't know what's wrong with my code.
Here's my algorithm:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
//base case
if (str.length() == 1)
perms.add(str);
else {
//loop over the string
for (int i = 0; i < str.length() - 1; i++) {
//make a subset of the string excluding the first char
String sub = str.substring(i + 1, str.length());
//compute permutations of the subset
ArrayList<String> subPerms = computeAllPossiblePermutations(sub);
//add the first char that we excluded at the start of each permutations
for (String s : subPerms) {
s = str.charAt(i) + s;
perms.add(s);
}
}
}
return perms;
}
There are a few issues:
The following line: String sub = str.substring(i+1, str.length()); ignores the first character
The same line also treats anything after index i as a "block" of substring that is left unchanged, while in order to generate permutation we should insert the current (first) character in between any two characters of the rest of the string - and do that for each permutation
The line s = str.charAt(i) + s; repeats the same mistake in #2
Here's a suggested fix:
public static ArrayList<String> computeAllPossiblePermutations(String str) {
ArrayList<String> perms = new ArrayList<>();
if (str.length() == 1) {
perms.add(str);
} else {
String chr = str.substring(0,1);
String rest = str.substring(1);
ArrayList<String> subPerms = computeAllPossiblePermutations(rest);
for (String s : subPerms) {
for (int j = 0; j <= s.length(); j++) {
String newPerm = s.substring(0,j) + chr + s.substring(j);
perms.add(newPerm);
}
}
}
return perms;
}

How to create a random word picker method [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm really new to java and just learning. I'm doing a java assignment and I don't quite understand; I am supposed to create a method that will take in a String array and return a randomly selected Sting from that array. here are the exact instructions:
*getRandomWord --> consumes an array of Strings and selects
(returns) one of the words at random.
signature: String getRandomWord (String [] array)
*
Then I think I have to create another method. I doubt an you have two methods named the same thing but the instructions say:*getRandomWord --> consumes an array of Strings and an integer (len).
This method selects a word from the array whose
length is more than len. If the length of the word
selected is less than len, then this method selects
another word at random. This is repeated 500 times
until a word is found/returned or no word is found
in which case this method will return null.
signature: String getRandomWord (String [] array, int len)
*
As I said I'm really new so help is appreciated.
Since this is an assignment I will only give you pointers to write the method yourself. The algorithm to use in String getRandomWord (String [] array)is elucidated below:
Calculate the length of the array. See How to find length of a string array
Generate the index of the random word from the array's length. See Getting random numbers in java
Get and return the random word from the array.
All these should be done in not more than 3 lines of code. Good Luck!
I would suggest to do it yourself. If you don't get, code is here :) Use the Random API. nextInt() method of Random method gives the Random value, which can be used as index to return random String from Arra.
Below is complete code of 2 methods:
import java.util.Random;
public class TestJava {
public static void main(String[] args) {
String[] strArray = { "first", "second", "third" };
System.out.println(getRandomWord(strArray));
}
static String getRandomWord(String[] array) {
Random random = new Random();
int index = random.nextInt(array.length);
return array[index];
}
static String getRandomWordWithLength(String[] array, int len) {
Random random = new Random();
for (int i = 0; i < 500; i++) {
int index = random.nextInt(3);
String selectedString = array[index];
if (selectedString.length() > len)
return selectedString;
}
return null;
}
}
Try to do yourself at first as it is an assignment. Take help from the code below if you failed it to do yourself.
private String getRandomWord(String[] array) {
int idx = new Random().nextInt(array.length);
return (array[idx]);
}
private String getRandomWord(String[] array, int len) {
String word = null;
for (int i = 1; i <= 500; i++) {
word = getRandomWord(array);
if (word.length() > len) {
break;
} else {
word = null;
}
}
return word;
}

Sequences in JAVA [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to generate this output :
aaa aaa aab aOa baa aaa aab c
given this sequence:
aaaab aOa baaab c
I'm really new to JAVA and I can't form the other sequences, just
aaa aaa aab
I've been trying for a month so that's why I'm asking here, can someone help me please?
Here is my code:
public void generateSequence(String text, int n)
{
text ="aaaab aOa baaab c";
n=3; //i.e
String[] words = text.split(" ");
StringBuilder newGram = new StringBuilder();
int p1 = 0;
int p2 = n;
String seq = "";
int seqLength = seq.length();
while (p1 < p2 && p2 <= seqLength) {
newGram = newGram.append(seq.substring(p1, p2) + " ");
p1++;
p2++;
if (p2 == seqLength) {
System.out.println("End of 1st element");
//Skip to the next elements in array and form sequences....
}
}
System.out.println(newGram);
}
This works for me.
public static void main(final String[] args) {
final String input = "aaaab aOa baaab c";
final String[] sections = input.split(" ");
final int length = 3;
final List<String> list = new ArrayList<>();
for (final String section : sections) {
for (int i = 0; i < section.length(); i++) {
if (section.length() < length) {
list.add(section);
continue;
}
final int end = i + length;
if (end > section.length()) {
break;
}
final String result = section.substring(i, end);
list.add(result);
}
}
list.stream().forEach(s -> System.out.println(s));
}
Ok user put some text now n is the number of subsequences generated from the text, as you may know text are words and i save them into words array.
now if u say pilot for n = 3
resulting array would be pil ilo lot
for n = 2
resulting array would be pi il lo ot
and so on
for example text = Java Rocks!
for n = 3
Jav ava Roc ock cks!
i want to generate n-gram according to some text as input and n for generating subsequences, could you put some code? thanks a lot.

String of Number with comma [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having issues when solving this problem:
Write a structures program that can accept two integer numbers up to 40 digit and perform the following:
add the two numbers together and display the result
the result number should should be seperated by commas.
So I was able to do number 1 using BigInteger, but for part 2 I am having issues. I don't know how I'm supposed to add a comma to a string, I was using a for loop to do with split but its not working.
I was able to figure it out thanks for all the help
public static String NewString (String num)
{
String sent = "" ;
int count = 0;
for ( int index = num.length()-1 ; index >= 0 ; index --)
{
count++;
sent = num.charAt(index) + sent;
if(count % 3 == 0 && index != 0)
sent = "," + sent;
}
return sent;
}
You can use
String formattedInteger = NumberFormat.getNumberInstance(Locale.US).format(bigInteger);
or you can write your own. It would be pretty simple, just convert your BigInteger to a String then loop through it backwards and every 3rd character you pass add a comma.
The code below -
Adds two numbers together and displays the result
The result number should be separated by commas.
Is quite self explanatory, Hope this helps :)
package stackoverflow;
import java.math.BigInteger;
/**
* Created by Nick on 11/13/14.
*
* Add two numbers together and display the result
* The result number should be separated by commas.
*/
public class SO_26916958 {
private static BigInteger arg1;
private static BigInteger arg2;
public static void main(String[] args) {
arg1 = new BigInteger (args[0].getBytes());
arg2 = new BigInteger (args[1].getBytes());
BigInteger sum = arg1.add(arg2);
String bigIntegerString = sum.toString();
String output = recursivelyAddComma(bigIntegerString);
System.out.print(bigIntegerString +"\n");
System.out.print(output);
}
private static String recursivelyAddComma (String s) {
int length = s.length();
StringBuilder output = null;
if(length <= 3) {
return s.toString();
}
return recursivelyAddComma(s.substring(0, length - 3)).concat(",").concat(s.substring(length - 3, length));
}
}

ArrayList Confusion and assistance! [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
basically id like a few hints or tips on how to solve this question.. maybe a few things which i could read up on about arraylists and loop which would make it simple for me to understand!..
the question is :
Processing an ArrayList of Characters:
cList is an ArrayList of objects of type Character that has been declared and intialised. Write a loop that will count the Characters that are not spaces and print the number out to the terminal window.
and second question would be:
Looping through a String
Assuming that a variable has been declared like this:
String s;
and that a value has already been assigned to s, write a loop statement that will print the characters of s in reverse order (so if s = "HELLO", your loop should print "OLLEH").
for the first question i tried to do:
public ArrayList()
public static void main(String[] args) {
int countBlank;
char ch;
public ArrayList (int cList)
{
int cList = ;
while(cList ){
System.out.println(cList);
}
}
and second question :
i have no idea, but a read up would be great!
thank you!
You could start by reading up on ArrayList Javadoc and documentation on mindprod.
In your example you haven't declared cList as arraylist nor filled it with Character objects. Instead of a while you might look into for. To get the characters in a String, String.toCharArray() might be of use.
For your first question, you want to loop through the list and count the number of times a character isn't a space.
int counter = 0;
for (Character c : characters) {
if (c == null {
continue; // Note: You can have null values in an java.util.ArrayList
}
if (!Character.isSpaceChar(c)) {
counter++;
}
}
System.out.println(counter);
For your second question:
for (int i = s.length() - 1; i >= 0; i--) {
System.out.print(s.charAt(i));
}
An arraylist is probably too fat for that:
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class CI {
private static final String text = "Hello";
public static void main(String[] args) {
CharacterIterator it = new StringCharacterIterator(text);
for (char ch = it.last(); ch != CharacterIterator.DONE; ch = it
.previous()) {
System.out.print(ch);
}
}
}
Answer to Question 1:
import java.util.*;
public class ProcessListOfChars{
public static int printCharsInListIgnoreSpaces(List<Character> cList){
int count =0;
for(Character character:cList){
// System.out.println("Value :"+character);
if(character!=null &&!character.toString().trim().equals("")){
++count;
}
}
return count;
}
public static void main(String... args){
List<Character> cList = new ArrayList<Character>();
cList.add('c'); //Autoboxed char to Charater Wrapper Class
cList.add(' '); //Space character
cList.add('r');
cList.add('b');
cList.add(' ');
int count = printCharsInListIgnoreSpaces(cList);
System.out.println("Count of Characers :"+count);
}
}

Categories

Resources