Separating a char from a String? - java

I am trying to separate the char from the following examples of inputs:
C450.00
C30
P100
I would like to have the char such as "C" or "P" separated so I can work with them alone,
as well as the "450.00", "30", and "100" separated as ints. What would be the easiest way to do this?

You can split the String with whitespace as delimiter. Afterwards use substring on every part of your string. Now you have the C and the 450.0 as Stings. Finally cast the second part of your substring into an integer and you are done.
to split:
String[] parts = string.split(" ");
to substring:
String first = parts[0].substring(0, 1);
String second = parts[0].substring(1);

If the String are always that format:
char ch = yourString.charAt(0);
Double d = Double.valueOf(yourString.substring(1, yourString.length()));
NOTE: I used a Double because you have dots . in the String. You can convert from double to int easily if you won't have any decimals. But that depends on your needings.

Assuming you know what are you looking for in the given String (eg. You know you are looking for the C character ) , you could use the Regex Pattern : https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

You can use this library org.​apache.​commons.​lang3.​StringUtils
http://commons.apache.org/proper/commons-lang/download_lang.cgi
public static String[] split(String str, String separatorChars)
String[] res = StringUtils.split("C450.00 C30 P100", "CP ");
for (String r : res) {
System.out.println(r);
}

I assume the separate 'numbers' are always in this format:
C130
P90
V2.0
that is, a single letter followed by a number (possibly with a floating point).
String input = "C450.00 C30 P100";
// First split the string by a space
String[] parts = input.split(" ");
for (String part : parts) {
// Get the character from the string
char ch = part.charAt(0);
// Get the remains of the string and convert it to a double
double number = Double.parseDouble(part.substring(1));
// Then do something with 'ch' and 'number'
}
If the separate parts possibly have two or more letters in it, e.g. AC130, then you need another approach:
String input = "AC130 AG36 P90";
String[] parts = input.split(" ");
for (String part : parts) {
/* Do some regular expression magic. */
}
See http://www.vogella.com/tutorials/JavaRegularExpressions/article.html.

here some piece of code:
public static void main(String[] args) {
String a = "C450.00 C30 P100";
String letters = "";
String numbers = "";
for (int i = 0; i < a.length(); i++) {
if ((a.charAt(i) + "").matches("\\d|\\.| ")) {
numbers += a.charAt(i);
} else {
letters += a.charAt(i);
}
}
String[] strArray = numbers.split(" ");
int[] numberArray = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
numberArray[i] = (int) Double.parseDouble(strArray[i]);
System.out.println(numberArray[i]);
}
System.out.println(letters);
}
the result is numberArray, which contains all numbers as ints.
and letters, which is a String with all letters.

Related

Java, extract integer values within defined characters from long string

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

Parse words separate by |

I have a string #JSGF V1.0;grammar numbers;public <accion> = (one| two| three);
I want the numbers: one, two and three.
I did this String answer = res.substring(res.indexOf("(")+1,res.indexOf(")")); and obtain one| two| three, but Im having trouble in this part.
Ideas?
You can get the numbers as array using
String numbers[] = answer.split("\\s*\\|\\s*");
\\s*\\|\\s*: 0 or more spaces then | symbol and 0 or more spaces
split the answer on non-word characters:
public static void main(String[] args) {
String res = "JSGF V1.0;grammar numbers;public <accion> = (one| two| three);";
String answer = res.substring(res.indexOf("(") + 1, res.indexOf(")"));
String[] numbers = answer.split("[^\\w]+"); // split on non-word character
for (String number : numbers) {
System.out.println(number);
}
}
output:
one
two
three
String res = "(one| two| three);";
String answer = res.substring(res.indexOf("(")+1,res.indexOf(")"));
for(String str : answer.split("\\s*\\|\\s*")) {
System.out.println(str);
}

A function that display the same text with two letters reversed

I'm trying to make an encryptor.What i want it to do:
Get the text i enter and reverse the first two letters of every word
and then display it again.
I have tried a lot of ways.This is the last one i've tried:
private void TranslateToEf(){
String storage = Display.getText();
String[] arr = storage.split("\\W+");
for ( String ss : arr) {
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
Display.appendText(swappedString + " ");
}
}
You may want to consider maintaining all the delimiters lost from the first String.split("\\W+") so they can be included in the final result. I would do that with a String.split("\\w+")
You may also want to consider that when you swap the first two letters, if the first letter is capital it becomes lowercase and the second letter becomes uppercase. Otherwise, just do a direct swap.
Code sample:
public static void main(String[] args) throws Exception {
String data = "Hello;World! My name is John. I write code.";
String[] words = data.split("\\W+");
String[] delimiters = data.split("\\w+");
int delimiterIndex = 0;
StringBuilder sb = new StringBuilder();
for (String word : words) {
if (word.length() < 2) {
sb.append(word);
} else {
char firstLetter = word.charAt(0);
char secondLetter = word.charAt(1);
if (Character.isUpperCase(firstLetter)) {
// Swap the first two letters and change casing
sb.append(Character.toUpperCase(secondLetter))
.append(Character.toLowerCase(firstLetter));
} else {
// Swap the first two letters
sb.append(secondLetter)
.append(firstLetter);
}
// Append the rest of the word past the first two letters
sb.append(word.substring(2));
}
// Append delimiters
if (delimiterIndex < delimiters.length) {
// Skip blank delimiters if there are any
while (delimiters[delimiterIndex].isEmpty()) {
delimiterIndex++;
}
// Append delimiter
sb.append(delimiters[delimiterIndex++]);
}
}
data = sb.toString();
// Display result
System.out.println(data);
}
Results:
Ehllo;Owrld! Ym anme si Ojhn. I rwite ocde.
public class Encrypto {
public static void main(String[] args) {
String input="Hello World";
String [] word = input.split(" ");
// System.out.println(word[0]);
String encryWord="";
for(int i=0;i<word.length;i++){
if (word[i].length() > 0) {
String tmp0 = String.valueOf(word[i].charAt(1));
String tmp1 = String.valueOf(word[i].charAt(0));
encryWord += tmp0.toLowerCase() + tmp1.toLowerCase() + word[i].substring(2) + " ";
}else{
encryWord +=word[i];
}
}
System.out.println(encryWord);
}
}
I think answer is more helpful for you
There are a few problems.
Declare zz outside the loop if you want to use it outside.
Append zz on every iteration. Not just assign it.
Something like this,
private void TranslateToEf(){
String storage = Display.getText();
String[] arr = storage.split("\\W+");
String zz = "";
for ( String ss : arr) {
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
String b= " ";
zz += swappedString + b;
}
Display.setText(zz + " ");
}
You are splitting with non-word (\W+) characters, but replacing it only with a space " ". This could alter the string with special characters.
Not sure what exactly you are looking for but i little modification in your code see if this suits your needs
String storage = "Test test t";
String[] arr = storage.split("\\W+");
String abc = "";
for ( String ss : arr) {
if(ss.length() > 1)
{
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String( c );
String b = " ";
String zz = swappedString + b;
abc = abc + zz;
}else{
abc = abc + ss;
}
}
System.out.println(abc);
In Java strings are immutable. You can't modify them "on the fly", you need to reassign them to a new instance.
Additionally, you are setting the last display text to zz, but zz is a local variable to your loop, and therefore it gets re-instantiated with every iteration. In other words, you would be assigning to display only the last word!
Here is what you have to do to make it work:
String storage = Display.getText();
String[] arr = storage.split("\\W+");
String[] newText = new String[arr.length];
for ( int i = 0; i<arr.length; i++) {
String original = arr[i];
String modified = ((char) original.charAt(1)) + ((char) original.charAt(0)) + original.substring(2);
newText[i] = modified;
}
//Join with spaces
String modifiedText = Arrays.asList(newText).stream().collect(Collectors.join(" "));
Display.setText(modifiedText);
Note that:
1) We are assuming all strings have at least 2 chars
2) that your splitting logic is correct. Can you think some edge cases where your regexp fails?

java replace correct number into letter

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");

Adding dot between two characters in java string

I have a string:
String x = "10";
Now I want to add . between the numbers and print it like this
1.0
How can I achieve this?
You can split the string into the first character and the rest of the string, and then insert a dot '.' in between, like this:
String res = x.substring(0,1)+"."+x.substring(1);
// ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^
// the first digit the rest of the string
You can also use replaceAll to do it on longer strings, like this:
String orig = "19,28,37,46";
System.out.println(orig.replaceAll("(\\d)(\\d)", "$1.$2"));
This prints
1.9,2.8,3.7,4.6
Use the DecimalFormat class to better decouple the value and its representation.
If the String is always a 2-digit number :
String result = x.charAt(0) + "." + x.charAt(1);
this function can accepts all number and returns a dotted string, with small touches it can accepts many in other types of data an return data with options
fun getStringWithDot(nums: Int): String {
var str = ""
val istr = nums.toString()
for (ch in istr.indices){
if (ch == istr.length-1){
str += istr.substring(0,1)
}else{
str += istr.substring(ch,ch+1) + "."
}
}
return str
}
public static void main(String args[])
{
Scanner S=new Scanner(System.in);
int arr[];
int number;
number=S.nextInt();
int length=Integer.toString(number).length();
arr=new int[length];
char arr2[];
arr2=new char[length];
int count=0;
char arr3[];
arr3=new char[length];
String Q=Integer.toString(number);
for(int i=0;i<arr3.length;i++)
{
System.out.print(Q.charAt(i)+".");
}
}

Categories