I have a variable of type StringBuffer which has certain numbers in it say,
StringBuffer newString = new StringBuffer("25 75 25");
Now if I want to separate this out in an integer array, how could i do it?
for(int i=0;i<numberOfItemsInTheStore;i++){
newString.append(values.charAt(0));
values.deleteCharAt(0);
char c = values.charAt(0);
if(c==' ' || values.length()==1){
values.deleteCharAt(0);
value[i] = Integer.parseInt(newString.toString());
newString.delete(0, newString.length());
System.out.println(value[i]);
}
}
What might be wrong in the program?
String[] splits = newString.toString().split(" ");
int[] arrInt = new int[splits.length];
int idx = 0;
for (String s: splits){
arrInt[idx++] = Integer.parseInt(s);
}
You can get String array easily and when you want to use elements as int values use Integer.parseInt() method
StringBuffer newString = new StringBuffer("25 75 25");
String [] strArr = newString.toString().split(" ");
System.out.println(Arrays.toString(strArr));
Related
I am working on a program and I will be asking the user to input a string full of characters with no spaces. I will then be splitting this string up into parts of three characters each, and I would like to populate an array with these new strings of three characters. So basically what I am asking is how would I create a method that takes an input string, splits it up into separate parts of three, then populates an array with it.
while (i <= DNAstrand.length()-3) {
DNAstrand.substring(i,i+=3));
}
This code will split the string up into parts of three, but how do I assign those values to an array in a method?
Any help is appreciated thanks!
Loop through and add all the inputs to an array.
String in = "Some input";
//in.length()/3 is automatically floored
String[] out = new String[in.length()/3];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
This will ignore the end of the String if it's length isn't a multiple of 3. The end can be found with:
String remainder = in.substring(i, in.length());
Finally, if you want the remainder to be part of the array:
String in = "Some input";
//This is the same as ceiling in.length()/3
String[] out = new String[(in.length()-1)/3 + 1];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
out[out.length-1] = in.substring(i, in.length());
Try this:
private static ArrayList<String> splitText(String text)
{
ArrayList<String> arr = new ArrayList<String>();
String temp = "";
int count = 0;
for(int i = 0; i < text.length(); i++)
{
if(count < 3)
{
temp += String.valueOf(text.charAt(i));
count++;
if(count == 3)
{
arr.add(temp);
temp = "";
count = 0;
}
}
}
if(temp.length() < 3)arr.add(temp);//in case the string is not evenly divided by 3
return arr;
}
You can call this method like this:
ArrayList<Strings> arrList = splitText(and the string you want to split);
i have an integer values as:
1299129912
i want to store it as
12
12
12
in the int v1,v2,v3;
i.e.,when ever 9909 occurs we need to separate the values individually. Is it possible in java. If so please anyone help me.
here is the code I'm trying
int l = 1299129912;
Pattern p = Pattern.compile("99");
Matcher m1 = p.matcher(l);
if (m1.matches()) {
System.out.println("\n");
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method matcher(CharSequence) in the type Pattern is not applicable for the arguments (int)
I suppose you already have the value as a String since 1234990912349909 is more that Integer.MAX_VALUE. Then you can split the string into String[] and do whatever you want with the separate values. E.g. call parseInt on each element.
String[] values = myIntString.split("9909");
for (String value: values) {
int v = Integer.parseInt(value);
}
Yes, it is very possible in java. Just convert the integer to a string and replace the 9909 with a space.
Example:
String s="1234990912349909";
s=s.replaceAll("9909","");
int a=Integer.parseInt(s);
System.out.println(a);
//output would be 12341234
If you know you are always going to have 3 integers named v1, v2, and v3 the following would work:
String[] numbers = l.toString().split("99");
int v1 = Integer.parseInt(numbers[0]);
int v2 = Integer.parseInt(numbers[0]);
int v3 = Integer.parseInt(numbers[0]);
However if you don't know in advance then it might be better to do it like this:
String[] numbers = l.toString().split("99");
int[] v = new int[numbers.length];
for (int i = 0; i < numbers.length; i++)
v[i] = Integer.parseInt(numbers[i]);
I found out this is the easiest way to show you how you can resolve your issue:
I included clear comments on every important step. Please check this:
int num = 1239012390;
// Convert int into a string
String str = String.valueOf(num);
// What separates the values
String toBremoved = "90";
String str1 = "";
// Declare a String array to store the final results
String[] finalStrings = new String[2];
// i will be used as an index
int i = 0;
do {
// Finds and separates the first value into another string
finalStrings[i] = str.substring(0, str.indexOf(toBremoved));
// removes the first number from the original string
str = str.replaceFirst(finalStrings[i], "");
// Remove the next separating value
str = str.replaceFirst(str.substring(str.indexOf(toBremoved), str.indexOf(toBremoved) + toBremoved.length()), "");
// increments the index
i++;
} while (str.indexOf(toBremoved) > 0); // keeps going for a new iteration if there is still a separating string on the original string
// Printing the array of strings - just for testing
System.out.println("String Array:");
for (String finalString : finalStrings) {
System.out.println(finalString);
}
// If you want to convert the values into ints you can do a standard for loop like this
// Lets store the results into an int array
int [] intResults = new int [finalStrings.length];
for (int j = 0; j < intResults.length; j++) {
intResults[j] = Integer.valueOf(finalStrings[j]);
}
// empty line to separate results
System.out.println();
// Printing the array of ints
System.out.println("int Array:");
for (int intResult : intResults) {
System.out.println(intResult);
}
Or in a simplified and more accurate way:
(you can use the example above if you need to understand how it can be done the long way)
int num = 1239012390;
String [] numbers = String.valueOf(num).split("90");
int num1 = Integer.parseInt(numbers[0]);
int num2 = Integer.parseInt(numbers[1]);
System.out.println("1st -> " + num1);
System.out.println("2nd -> " + num2);
How do I split a string with numbers?
Like if I have "20 40" entered, how do I split
it so I get 20, 40?
int t = Integer.parseInt(x);
int str = t;
String[] splited = str.split("\\s+");
My code.
If you're trying to parse a string that contains whitespace-delimited integer tokens, into an int array, the following will work:
String input = "20 40";
String[] tokens = input.split(" ");
int[] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
numbers[i] = Integer.parseInt(tokens[i].trim());
}
You can also do this in a one-liner through the Iterables and Splitter utilities from the amazing Google Guava library:
Integer[] numbers = Iterables.toArray(Iterables.transform(
Splitter.on(' ').trimResults().split(input),
new Function<String, Integer>() {
#Override
public Integer apply(String token) {
return Integer.parseInt(token);
}
}), Integer.class);
You need to convert it to String value and then split, maybe like this:
String[] splited = String.valueOf(str).split("\\s+");
It seems you are reading the number as String and trying to convert it to integer before the split here:
int t = Integer.parseInt(x);
so you can actually split your variable x and get the indiviudal int values out of it like this:
String[] splited = x.split("\\s+");
for(String num:splited) {
int intVal = Integer.valueOf(num);
}
Could smb please explaing the process of sorting characters of String alphabetically? For example, if I have String "hello" the output should be "ehllo" but my code is doing it wrong.
public static void main(String[] args)
{
String result = "";
Scanner kbd = new Scanner(System.in);
String input = kbd.nextLine();
for(int i = 1; i < input.length(); i++)
{
if(input.charAt(i-1) < input.charAt(i))
result += input.charAt(i-1);
//else
// result += input.charAt(i);
}
System.out.println(result);
}
}
You may do the following thing -
1. Convert your String to char[] array.
2. Using Arrays.sort() sort your char array
Code snippet:
String input = "hello";
char[] charArray = input.toCharArray();
Arrays.sort(charArray);
String sortedString = new String(charArray);
System.out.println(sortedString);
Or if you want to sort the array using for loop (for learning purpose) you may use (But I think the first one is best option ) the following code snippet-
input="hello";
char[] charArray = input.toCharArray();
length = charArray.length();
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if (charArray[j] < charArray[i]) {
char temp = charArray[i];
charArray[i]=arr[j];
charArray[j]=temp;
}
}
}
You can sort a String in Java 8 using Stream as below:
String sortedString =
Stream.of("hello".split(""))
.sorted()
.collect(Collectors.joining());
Procedure :
At first convert the string to char array
Then sort the array of character
Convert the character array to string
Print the string
Code snippet:
String input = "world";
char[] arr = input.toCharArray();
Arrays.sort(arr);
String sorted = new String(arr);
System.out.println(sorted);
Sorting as a task has a lower bound of O(n*logn), with n being the number of elements to sort. What this means is that if you are using a single loop with simple operations, it will not be guaranteed to sort correctly.
A key element in sorting is deciding what you are sorting by. In this case its alphabetically, which, if you convert each character to a char, equates to sorting in ascending order, since a char is actually just a number that the machine maps to the character, with 'a' < 'b'. The only gotcha to look out for is mixed case, since 'z' < 'A'. To get around, this, you can use str.tolower(). I'd recommend you look up some basic sorting algorithms too.
Your for loop is starting at 1 and it should be starting at zero:
for(int i = 0; i < input.length(); i++){...}
You can do this using Arrays.sort, if you put the characters into an array first.
Character[] chars = new Character[str.length()];
for (int i = 0; i < chars.length; i++)
chars[i] = str.charAt(i);
// sort the array
Arrays.sort(chars, new Comparator<Character>() {
public int compare(Character c1, Character c2) {
int cmp = Character.compare(
Character.toLowerCase(c1.charValue()),
Character.toLowerCase(c2.charValue())
);
if (cmp != 0) return cmp;
return Character.compare(c1.charValue(), c2.charValue());
}
});
Now build a string from it using StringBuilder.
Most basic and brute force approach using the two for loop:
It sort the string but with the cost of O(n^2) time complexity.
public void stringSort(String str){
char[] token = str.toCharArray();
for(int i = 0; i<token.length; i++){
for(int j = i+1; j<token.length; j++){
if(token[i] > token[j]){
char temp = token[i];
token[i] = token[j];
token[j] = temp;
}
}
}
System.out.print(Arrays.toString(token));
}
public class SortCharcterInString {
public static void main(String[] args) {
String str = "Hello World";
char[] arr;
List<Character> L = new ArrayList<Character>();
for (int i = 0; i < str.length(); i++) {
arr = str.toLowerCase().toCharArray();
L.add(arr[i]);
}
Collections.sort(L);
str = L.toString();
str = str.replaceAll("\\[", "").replaceAll("\\]", "")
.replaceAll("[,]", "").replaceAll(" ", "");
System.out.println(str);
}
For instance, if I have the string "Bob Bakes Brownies", is there any way I can get this method to produce a list of three strings: "Bob", "Bob Bakes", and "Bob Bakes Brownies"
Any feed back would be appreciated.
Create a list to return. Loop through the String looking for spaces. For each space that you find, add a substring to the list, that starts at the zero index and goes up to the space (not including the space).
When there are no more spaces, add the entire string to the list, and return.
You can use .split() to get an array of the individual words or use StringTokenizer
Good approach will be split(" ") the string, this will produce an array. Then you can iterate on the array when every time you concatenate the current array cell with StringBuilder or a normal concatenation and print the result on every iteration.
public void listOfStrings(String s){
ArrayList<String> result = new ArrayList<String>();
int p = 0;
for (int i = 0; i < s.length() ; i++) {
if(s.charAt(i) == ' ') {
result.add(p, s.substring(0, i));
p++;
}
if(i == s.length()-1)
result.add(p,s);
}
}
Try this:
static List<String> createStringList(String string) {
String[] parts = string.split(" ");
List<String> result = new ArrayList<>();
StringBuilder currentString = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) {
currentString.append(" ");
}
currentString.append(parts[i]);
result.add(currentString.toString());
}
return result;
}
public ArrayList<String> solution(String s){
ArrayList<String> result = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
String[] array = s.split(" ");
for(String str:array){
sb.append(str);
result.add(sb.toString());
}
return result;
}
String string = "Bob Bakes Brownies";
List<String> list = Arrays.asList(string.split(" "));