I have a program where I receive a long string in the format
characters$xxx,characters$xx,characters$xx, (....)
x is some digit of some integer with an arbitrary number of digits. The integer values are always contained within $ and ,.
I need to extract the integers into an integer array then print that array. The second part is easy, but how to extract those integers?
an example string: adsdfsh$1234,khjdfd$356,hsgadfsd$98,ghsdsk$4623,
the arraay should contain 1234, 356, 98, 4623
below is my basic logic
import java.util.Scanner;
class RandomStuff {
public static void main (String[]args){
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
int count =0;
// counts number of $, because $ will always preceed an int in my string
for(int i=0;i<input.length();i++ ){
if (input.charAt(i)=='$')
count++;}
/* also I'm traversing the string twice here so my complexity is at least
o(2n) if someone knows how to reduce that, please tell me*/
int [] intlist = new int[count];
// fill the array
int arrayindex =0;
for (int i=0; i<input.length();i++){
if (input.charAt(i)=='$'){
/*insert all following characters as a single integer in intlist[arrayindex]
until we hit the character ','*/}
if (input.charAt(i)==','){
arrayindex++;
/*stop recording characters*/}
}
// i can print an array so I'll just omit the rest
keyboard.close();
}
You can use a regular expression with a positive lookbehind to find all consecutive sequences of digits preceded by a $ symbol. Matcher#results can be used to get all of the matches.
String str = "adsdfsh$1234,khjdfd$356,hsgadfsd$98,ghsdsk$4623";
int[] nums = Pattern.compile("(?<=\\$)\\d+").matcher(str).results()
.map(MatchResult::group)
.mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(nums));
It can done like this
var digitStarts = new ArrayList<Integer>()
var digitsEnds = new ArrayList<Integer>()
// Get the start and end of each digit
for (int i=0; i<input.length();i++){
if(input[i] == '$' ) digitsStarts.add(i)
if(input[i] == ',') digitEnds.add(i)
}
// Get the digits as strings
var digitStrings = new ArrayList<String>()
for(int i=0;i<digitsStart.length; i++ ) {
digitsString.add(input.substring(digitsStarts[i]+1,digitEnds[i]))
}
// Convert to Int
var digits = new ArrayList<Int>
for(int i=0;i<digitString;i++) {
digits.add(Integer.valueOf(digitStrings[i]))
}
In a very simple way:
public static void main(String[] args) {
String str = "adsdfsh$1234,khjdfd$356,hsgadfsd$98,ghsdsk$4623";
String strArray[] = str.split(",");
int numbers[] = new int[strArray.length];
int j = 0;
for(String s : strArray) {
numbers[j++] = Integer.parseInt(s.substring(s.indexOf('$')+1));
}
for(j=0;j<numbers.length;j++)
System.out.print(numbers[j]+" ");
}
OUTPUT: 1234 356 98 4623
Related
This is my raw code
int n1=nextInt();
String ch=next().split("");
int n2=nextInt().split("");
if i want to get input line 5A11 (in same line).What should i do to get input like this.IS it possible to get input like this in java
Read the input as a String. Then use below code to remove the characters from the String followed by summing the integers.
String str = "123ABC4";
int sum = str.replaceAll("[\\D]", "")
.chars()
.map(Character::getNumericValue)
.sum();
System.out.println(sum);
You can use String#split.
int[] parseInput(String input) {
final String[] tokens = input.split("A"); // split the string on letter A
final int[] numbers = new int[tokens.length]; // create a new array to store the numbers
for (int i = 0; i < tokens.length; i++) { // iterate over the index of the tokens
numbers[i] = Integer.parseInt(tokens[i]); // set each element to the parsed integer
}
return numbers;
}
Now you can use it as
int[] numbers;
numbers = parseInput("5A11");
System.out.println(Arrays.toString(numbers)); // output: [5, 11]
numbers = parseInput("123A456");
System.out.println(Arrays.toString(numbers)); // output: [123, 456]
String input = "123C567";
String[] tokens = input.split("[A-Z]");
int first = Integer.parseInt(tokens[0]);
int second = Integer.parseInt(tokens[1]);
I tried to count the occurrence of alphabets in a string, but I substitue them with numbers to make it clearer. Then when I run that code, it doesnt display the results I want.I dont really know why...Please help!! Thank you so much!!
Scanner Scanner1 = new Scanner(System.in);
out.println("Please type in a string below.");
String UserInput = Scanner1.nextLine();
String Index = "12345";
int length = 2;//Modified
int[] count = new int[length];
int length2 = 5; //Modified
int n1 = 0;
int n2 = 0;
out.println(UserInput.charAt(n1));//Modified
out.println(Index.charAt(n2));//Modified
for (int i = 0; i < length; i++) {
if (UserInput.charAt(n1) == Index.charAt(n2)) {
n1++;
count[length - (length - n1)]++;
} else {
n2++;
if(n2==length2)
{
n2 = n2-length2;
}
}
}
A relatively short and neat way to count a specific character in a string is using the return value of the replaceAll method:
public static int countChar(final String str, final char c) {
return str.replaceAll("[^" + c + "]","").length();
}
The pattern [^x] (x can be replaced with any char (or amount of different chars)) will match everything in a given String except x. So [^T] of TEST would replace E and S with the given replacement (which is "" (nothing)) and keeps the Ts. The method would return TT. If you count that length, you'll receive the count of the searched character of the given string.
The example
System.out.println(countChar("TEST", 'T'));
System.out.println(countChar("TEST", 'E'));
System.out.println(countChar("TEST", 'S'));
prints
2
1
1
(keep in mind that is method is case sensitive)
use collections like Hashmap. Here Character stores every unique character encountered and Integer stores the count of every character whenever it is encountered.
I've got this bit of code here:
public class Project1 {
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Input a binary number");
String binary = input.nextLine();
System.out.println(Conversion(binary));
}
public static int Conversion(String binary)
{
StringTokenizer st = new StringTokenizer(binary, " ");
int n = st.countTokens() - 1; // Used as the power number in b^n for conversion
int result = 0;
while(st.hasMoreTokens()){
int binaryInt = Integer.parseInt(st.nextToken());
result += binaryInt * (1 << n);
n--;
}
return result;
}
}
And it works beautifully... if the input has spaces in between the binary numbers. For example, if the input is 1 1 1 1, then it will rightfully return 15. Cool, but how do I change the tokenizer to not require spaces to split each digit? I tried doing StringTokenizer(binary, ""); and StringTokenizer(binary);, but neither properly split each digit into it's own token.
You will notice that, while StringTokenizer obviously only works with Strings, I've converted the Strings into ints inside my conversion method before returning the result.
# Tony I think you tried to add the ascii values of the digits here
for input value 10
for first run
int binaryInt = binary.char(i) ; so binaryInt would get the value = 49(aski value of char '1')
hence result = 49*2 = 98
in second run
result = 98 + 48 *1 = 146
following function will serve your purpose, for input String "1101" , it returns 13
public int getDecimal(String binaryString){
//binaryString = "1101";
int result = 0;
int n = binaryString.length()-1;
for(int i=0;i<binaryString.length();i++)
{
int num = binaryString.charAt(i);
if(num>=48 && num <=57){
result+=(num-48) * Math.pow(2, n) ;
n --;
}
}
return result;
}
}
How about something like this:
// remove everything that is not a digit
String digitsOnly = binary.replaceAll("[^\\d]","");
//iterate over every digit
for(char digit:digitsOnly.toCharArray()) {
int n = Character.getNumericValue(digit);
// do stuff...
}
If you get a string like "10011010", you don't need a tokenizer, you can just iterate over the string and use charAt:
for (int i = 0; i < s.length(); i++) {
char currentDigit = s.charAt(i);
// Do stuff with the digit
}
Well, this is my first time get here.
I'm trying to figure out the correct way to replace number into letter.
In this case, I need two steps.
First, convert letter to number. Second, restore number to word.
Words list: a = 1, b = 2, f = 6 and k = 11.
I have word: "b a f k"
So, for first step, it must be: "2 1 6 11"
Number "2 1 6 11" must be converted to "b a f k".
But, I failed at second step.
Code I've tried:
public class str_number {
public static void main(String[] args){
String word = "b a f k";
String number = word.replace("a", "1").replace("b","2").replace("f","6").replace("k","11");
System.out.println(word);
System.out.println(number);
System.out.println();
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
System.out.println(number);
System.out.println(text);
}
}
Result:
b a f k
2 1 6 11
2 1 6 11
b a f aa
11 must be a word "k", but it's converted to "aa"
What is the right way to fix this?
Or do you have any other ways to convert letter to number and vice versa?
Thank you.
It would be good to write methods for conversion between number and letter format. I would write some code like this and use it generally instead of hard coding replace each time.
public class test {
static ArrayList <String> letter = new ArrayList<String> ();
static ArrayList <String> digit = new ArrayList<String> ();
public static void main(String[] args) {
createTable();
String test="b a f k";
String test1="2 1 6 11";
System.out.println(letterToDigit(test));
System.out.println(digitToLetter(test1));
}
public static void createTable()
{
//Create all your Letter to number Mapping here.
//Add all the letters and digits
letter.add("a");
digit.add("1");
letter.add("b");
digit.add("2");
letter.add("c");
digit.add("3");
letter.add("d");
digit.add("4");
letter.add("e");
digit.add("5");
letter.add("f");
digit.add("6");
letter.add("g");
digit.add("7");
letter.add("h");
digit.add("8");
letter.add("i");
digit.add("9");
letter.add("j");
digit.add("10");
letter.add("k");
digit.add("11");
letter.add("l");
digit.add("12");
letter.add("m");
digit.add("13");
letter.add("n");
digit.add("14");
letter.add("o");
digit.add("14");
letter.add("p");
digit.add("15");
//Carry so on till Z
}
public static String letterToDigit(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(letter.contains(individual[i])){
result+=Integer.toString(letter.indexOf(individual[i])+1)+ " ";
}
}
return result;
}
public static String digitToLetter(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(digit.contains(individual[i])){
result+=letter.get(digit.indexOf(individual[i])) + " ";
}
}
return result;
}
}
I would actually not use replace in this case.
A more generic solution would be to simply convert it to a char and subtract the char a from it.
int n = word.charAt(0) - 'a' + 1;
This should return an int with the value you are looking for.
If you want this to be an string you can easily do
String s = Integer.parseInt(word.charAt(0) - 'a' + 1);
And as in your case you are doing a whole string looping through the length of it and changing all would give you the result
String s = "";
for(int i = 0; i < word.length(); i++) {
if(s.charAt(i) != ' ') {
s = s + Integer.toString(word.charAt(i) - 'a' + 1) + " ";
}
}
and then if you want this back to an String with letters instead
String text = "";
int temp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ' ') {
text = text + String.valueOf((char) (temp + 'a' - 1));
temp = 0;
} else if {
temp = (temp*10)+Character.getNumericValue(s.charAt(i));
}
}
You can just reverse the replacement:
String text = number.replace("11","k").replace("2","b").replace("6","f").replace("1","a");
Simplest solution IMO.
When adding other numbers, first replace these with two digits, then these with one.
Replace this:
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
By this:
String text = number.replace("11","k").replace("1", "a").replace("2","b").replace("6","f");
Right now, the first replace you're doing: ("1", "a")
is invalidating the last one: ("11","k")
I think you would need to store the number as an array of ints. Otherwise, there is no way of knowing if 11 is aa or k. I would create a Map and then loop over the characters in the String. You could have one map for char-to-int and one for int-to-char.
Map<Character,Integer> charToIntMap = new HashMap<Character,Integer>();
charToIntMap.put('a',1);
charToIntMap.put('b',2);
charToIntMap.put('f',6);
charToIntMap.put('k',11);
Map<Integer,Character> intToCharMap = new HashMap<Integer,Character>();
intToCharMap.put(1,'a');
intToCharMap.put(2,'b');
intToCharMap.put(6,'f');
intToCharMap.put(11,'k');
String testStr = "abfk";
int[] nbrs = new int[testStr.length()];
for(int i = 0; i< testStr.length(); i++ ){
nbrs[i] = charToIntMap.get(testStr.charAt(i));
}
StringBuilder sb = new StringBuilder();
for(int num : nbrs){
sb.append(num);
}
System.out.println(sb.toString());
//Reverse
sb = new StringBuilder();
for(int i=0; i<nbrs.length; i++){
sb.append(intToCharMap.get(nbrs[i]));
}
System.out.println(sb.toString());
This failed because the replace("1", "a") replaced both 1s with a characters. The quickest fix is to perform the replace of all the double-digit numbers first, so there are no more double-digit numbers left when the single-digit numbers get replaced.
String text = number.replace("11","k").replace("1", "a").
replace("2","b").replace("6","f");
i tried myself lot but can't get a solution so i'm asking help.
i have an string String input="---4--5-67--8-9---";
now i need to convert in into an string array which will look like:
String [][]output={{4},{5},{67},{8},{9}};
i tried with split() and
java.util.Arrays.toString("---4--5-67--8-9---".split("-+")
but can't find the desired answer. so what to do?
actually i need the value 4,5,67,8,9.but i'm not sure how to find them. i will treat the values as integer for further processing
String[] numbers = "---4--5-67--8-9---".split("-+");
String[][] result = new String[numbers.length][1];
for (int i = 0; i < numbers.length; i++) {
result[i][0] = numbers[i];
}
Update: to get rid of the initial empty value, you can get a substring of the input, like:
int startIdx = 0;
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i ++) {
if (Character.isDigit(chars[i])) {
startIdx = i;
break;
}
}
input = input.substring(startIdx);
(or you can check them for not being empty (String.isEmpty()) when processing them later.)
First, here is the answer to your question. This code will generate a two-dimensional array where each element is an array consisting of a single numeric string.
final String input = "---4--5-67--8-9---";
// desired output: {{4},{5},{67},{8},{9}}
// First step: convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create the two-dimensional array with the correct size
final String[][] arrayOfArrays = new String[arrayOfStrings.length][];
// Loop over single-dimension array to initialize the two-dimensional one
for(int i = 0; i < arrayOfStrings.length; i++){
final String item = arrayOfStrings[i];
arrayOfArrays[i] = new String[] { item };
}
System.out.println(Arrays.deepToString(arrayOfArrays));
// Output: [[4], [5], [67], [8], [9]]
However, I think what you really need is an array of Integers or ints, so here is a revised solution:
final String input = "---4--5-67--8-9---";
// Convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create an array of Integers and assign the values from the string
final Integer[] arrayOfIntegers = new Integer[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfIntegers[i] = Integer.valueOf(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfIntegers));
// Output: [4, 5, 67, 8, 9]
// Or alternatively an array of ints
final int[] arrayOfInts = new int[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfInts[i] = Integer.parseInt(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfInts));
// Output: [4, 5, 67, 8, 9]
Whether you use the Integer or the int version really depends on whether you want to just do some math (int) or need an object reference (Integer).
String[] result = "---4--5-67--8-9---".split("-+");
int i;
for (i = 0; i < result.length; i++) {
if (result[i].length() > 0) {
System.out.println(result[i]);
}
}
gives me output:
4
5
67
8
9
public class split{
public static void main(String[] argv){
String str="---4--5-67--8-9---";
String[] str_a=str.split("-+");
}
}
This seems to working for me.
Using a regex pattern seems more natural in this case:
public class split {
public static int[] main(String input) {
ArrayList<String> list = new ArrayList() ;
Pattern pattern = Pattern.compile("[0-9]") ;
Matcher matcher = pattern.matcher(input) ;
String match = null ;
while( ( match = matcher.find() ) === true ) {
list.add(match) ;
}
String[] array = list.toArray( new String[ ( list.size() ) ]() ) ;
return array ;
}
}
String input="---4--5-67--8-9---";
Scanner scanner = new Scanner(input).useDelimiter("-+");
List<Integer> numbers = new ArrayList<Integer>();
while(scanner.hasNextInt()) {
numbers.add(scanner.nextInt());
}
Integer[] arrayOfNums = numbers.toArray(new Integer[]{});
System.out.println(Arrays.toString(arrayOfNums));
I thought the following is quite simple, although it uses List and Integer arrays, Its not that an overhead for small strings:
For simplicity, I am returning a single dimension array, but can be easily modified to return an array you want. But from your question, it seems that you just want a list of integers.
import java.util.*;
public class Test {
public static void main(String[] args) throws Throwable {
String input = "---4--5-67--8-9---";
System.out.println(split(input).length); // 5
}
public static Integer[] split(String input) {
String[] output = input.split("\\-+");
List<Integer> intList = new ArrayList<Integer>(output.length);
// iterate to remove empty elements
for(String o : output) {
if(o.length() > 0) {
intList.add(Integer.valueOf(o));
}
}
// convert to array (or could return the list itself
Integer[] ret = new Integer[intList.size()];
return intList.toArray(ret);
}
}
I might be late to the party but I figured I'd give the guava take on this.
String in = "---4--5-67--8-9---";
List<String> list = Lists.newArrayList(Splitter.on("-").omitEmptyStrings().trimResults().split(in));
System.out.println(list);
// prints [4, 5, 67, 8, 9]