Separate number from a string - java

I want to get the numbers of a given string and I used the code as below
String sample = "7011WD";
String output = "";
for (int index = 0; index < sample.length(); index++)
{
if (Character.isDigit(sample.charAt(index)))
{
char aChar = sample.charAt(index);
output = output + aChar;
}
}
System.out.println("output :" + output);
The Result is:
output :7011
Is there any simple way to get the output?

Is there any simple way to get the output
May be you could use a regex \\D+ (D is anything which is not a digit , + means one or more occurence), and then String#replaceAll() all non-digits with empty string:
String sample = "7011WD";
String output = sample.replaceAll("\\D+","");
Though remember, using regex is not efficient at all . Also , this regex will remove the decimal points too !
You need to use Integer#parseInt(output) or Long#parseLong(output) to get the primitive int or long respectively.
You can also use Google's Guava CharMatcher. Specify the range using inRange() and return the characters from that range in sequence as a String using retainFrom().

Also you can use ASCII to do this
String sample = "7011WD";
String output = "";
for (int index = 0; index < sample.length(); index++)
{
char aChar = sample.charAt(index);
if(int(aChar)>=48 && int(aChar)<= 57)
output = output + aChar;
}
}
System.out.println("output :" + output);

Related

split a string when there is a change in character without a regular expression

There is a way to split a string into repeating characters using a regex function but I want to do it without using it.
for example, given a string like: "EE B" my output will be an array of strings e.g
{"EE", " ", "B"}
my approach is:
given a string I will first find the number of unique characters in a string so I know the size of the array. Then I will change the string to an array of characters. Then I will check if the next character is the same or not. if it is the same then append them together if not begin a new string.
my code so far..
String myinput = "EE B";
char[] cinput = new char[myinput.length()];
cinput = myinput.toCharArray(); //turn string to array of characters
int uniquecha = myinput.length();
for (int i = 0; i < cinput.length; i++) {
if (i != myinput.indexOf(cinput[i])) {
uniquecha--;
} //this should give me the number of unique characters
String[] returninput = new String[uniquecha];
Arrays.fill(returninput, "");
for (int i = 0; i < uniquecha; i++) {
returninput[i] = "" + myinput.charAt(i);
for (int j = 0; j < myinput.length - 1; j++) {
if (myinput.charAt(j) == myinput.charAt(j + 1)) {
returninput[j] += myinput.charAt(j + 1);
} else {
break;
}
}
} return returninput;
but there is something wrong with the second part as I cant figure out why it is not beginning a new string when the character changes.
You question says that you don't want to use regex, but I see no reason for that requirement, other than this is maybe homework. If you are open to using regex here, then there is a one line solution which splits your input string on the following pattern:
(?<=\S)(?=\s)|(?<=\s)(?=\S)
This pattern uses lookarounds to split whenever what precedes is a non whitespace character and what proceeds is a whitespace character, or vice-versa.
String input = "EE B";
String[] parts = input.split("(?<=\\S)(?=\\s)|(?<=\\s)(?=\\S)");
System.out.println(Arrays.toString(parts));
[EE, , B]
^^ a single space character in the middle
Demo
If I understood correctly, you want to split the characters in a string so that similar-consecutive characters stay together. If that's the case, here is how I would do it:
public static ArrayList<String> splitString(String str)
{
ArrayList<String> output = new ArrayList<>();
String combo = "";
//iterates through all the characters in the input
for(char c: str.toCharArray()) {
//check if the current char is equal to the last added char
if(combo.length() > 0 && c != combo.charAt(combo.length() - 1)) {
output.add(combo);
combo = "";
}
combo += c;
}
output.add(combo); //adds the last character
return output;
}
Note that instead of using an array (has a fixed size) to store the output, I used an ArrayList, which has a variable size. Also, instead of checking the next character for equality with the current one, I preferred to use the last character for that. The variable combo is used to temporarily store the characters before they go to output.
Now, here is one way to print the result following your guidelines:
public static void main(String[] args)
{
String input = "EEEE BCD DdA";
ArrayList<String> output = splitString(input);
System.out.print("[");
for(int i = 0; i < output.size(); i++) {
System.out.print("\"" + output.get(i) + "\"");
if(i != output.size()-1)
System.out.print(", ");
}
System.out.println("]");
}
The output when running the above code will be:
["EEEE", " ", "B", "C", "D", " ", "D", "d", "A"]

How to retain matched sub string and replace unmatched sub strings in Java String

Hello I try to print in an array of Strings
In the following way:
Input: big = "12xy34", small = "xy" output: "** xy **"
Input: big = "" 12xt34 "", small = "xy" output: "******"
Input: big = "12xy34", small = "1" output: "1 *****"
Input: big = "12xy34xyabcxy", small = "xy" output: "** xy ** xy *** xy"
Input: big = "78abcd78cd", small = "78" output: "78 **** 78 **"
What I need to write a condition to receive as up?
public static String stars(String big, String small) {
//throw new RuntimeException("not implemented yet ");
char[] arr = big.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (big.contains(small) ) {
arr[i] = '*';
}
}
String a = Arrays.toString(arr);
return big+""+a;
}
Algorithm:
Convert big and small String's to char[] array's bigC and smallC respectively
Iterate over each character of big String
At every index during iteration, identify whether there is a sub-string possible beginning current character
If there is a sub-string possibility, advance the index in big String iteration by length of small String
Otherwise, replace the character by *
Code:
public class StringRetainer {
public static void main(String args[]) {
String big[] = {"12xy34", "12xt34", "12xy34", "12xy34xyabcxy", "78abcd78cd"};
String small[] = {"xy", "xy", "1", "xy", "78"};
for(int i = 0; i < big.length & i < small.length; i++) {
System.out.println("Input: big = \"" + big[i] + "\", small = \"" + small[i] + "\" output : \"" + stars(big[i], small[i]) + "\"");
}
}
public static String stars(String big, String small) {
//String to char[] array conversions
char[] bigC = big.toCharArray();
char[] smallC = small.toCharArray();
//iterate through every character of big String and selectively replace
for(int i = 0; i < bigC.length; i++) {
//flag to determine whether small String occurs in big String
boolean possibleSubString = true;
int j = 0;
//iterate through every character of small String to determine
//the possibility of character replacement
for(; j < smallC.length && (i+j) < bigC.length; j++) {
//if there is a mismatch of at least one character in big String
if(bigC[i+j] != smallC[j]) {
//set the flag indicating sub string is not possible and break
possibleSubString = false;
break;
}
}
//if small String is part of big String,
//advance the loop index with length of small String
//replace with '*' otherwise
if(possibleSubString)
i = i+j-1;
else
bigC[i] = '*';
}
big = String.copyValueOf(bigC);
return big;
}
}
Note:
This is one possible solution (legacy way of doing)
Looks like there is no straight forward way of making this happen using built-in String/StringBuffer/StringBuilder methods

Java - Reverse String null error

The input is meant to appear like this, example.
\n
Kazan R
\n
6789
\n
Nzk462
\n
However the output I receive looks like this
kzn462nullnzk
Why is this? and How can i solve it?
private void btnGenerateActionPerformed(java.awt.event.ActionEvent evt) {
secondname = JOptionPane.showInputDialog("Enter your surname:");
firstname = JOptionPane.showInputDialog("Enter your firstname:");
idno = JOptionPane.showInputDialog("Enter your idno:");
nametag = firstname.substring(0, 1);
initials = secondname + " " + nametag;
int randnum;
do {
randnum = (int) (Math.random() * 900) + 100;
} while (randnum % 2 != 0);
code = secondname.replaceAll("[aeiou || AEIOU](?!\\b)", "")+randnum ;
txaDisplay.append(initials + '\n' + idno.substring(6,10) + '\n' + code);
int length = secondname.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + secondname.charAt(i);
}
String end = reverse + code;
txaDisplay.append( reverse);
Why don't you use
new StringBuilder(secondname).reverse().toString()
to reverse your String? It's better, simple and more maintanable.
Get the character array from your source string
Create a new char array of same length
Start iterating from 0 to (sourceStringLength-1)
In each iteration, get the last character
from the end in your source array and populate in your new array
Create a new string from this new array
String source = "abcdefg";
char[] chars = source.toCharArray();
char[] reverseChars = new char[source.length()];
int len = source.length();
for(int i= 0; i < len; i++){
reverseChars[i] = chars[len-1-i];
}
String reverse = new String(reverseChars);
System.out.println(reverse);
Since You don't want to use StringBuilder/StringBuffer.
Try this
String reversedString="";
for(int i=inputString.length-1;i>=0;){
reversedString+=inputString.charAt(i--);
}
I think the problem is your definition of reverse, maybe you have something like:
String reverse;
Then you don't initialize your "reverse" so when your program makes the first concatenation in your loop, it looks like this:
reverse = null + secondname.charAt(i);
The null value is converted to a string so it can be visible in the output.
I hope this information helps you.
Good Luck.

What is the way to insert a colon(:) after every two characters in a string?

I am trying to figure out that -
INPUT: String data = "506313B5EA3E";
OUTPUT: String data = "50:63:13:B5:EA:3E";
I tried using-
java.util.Arrays.toString(data.split("(?<=\\G..)"))
But the output is: [50, 6313B5EA3E]
You can use a RegExp:
String input = "0123456789abcdef";
String output = input.replaceAll("..(?!$)", "$0:")
// output = "01:23:45:67:89:ab:cd:ef"
How does it work?
.. matches exactly two characters. (?!$) ensures that these two characters are not at the end of input (?! is a negative lookahead, $ stands for the end).
The matching two characters will now be replaced by themselves ($0 means the whole matching string) and the colon we want.
Since we are using replaceALL, this operation repeats for every two-character group. Remember: except the last one.
Two simple options involving loops, both assuming you have already checked that the input is non-empty and has an even number of characters:
Use StringBuilder
StringBuilder builder = new StringBuilder(data.length() * 3 / 2 - 1);
for (int i = 0; i < data.length(); i += 2) {
if (i != 0) {
builder.append(":");
}
builder.append(data.substring(i, i + 2));
}
String text = builder.toString();
Use a char array
char[] output = new char[data.length() * 3 / 2 - 1];
int outputIndex = 0;
for (int i = 0; i < data.length(); i += 2) {
if (i != 0) {
output[outputIndex++] = ':';
}
output[outputIndex++] = data.charAt(i);
output[outputIndex++] = data.charAt(i + 1);
}
String text = new String(output);
Another option would be to use Joiner from Guava along with your previous split:
String text = Joiner.on(':').join(data.split("(?<=\\G..)"));

Finding Data within a String

I'm trying to find a way to cycle through a string and get data within two characters, for example... I have the following String.
String test = "<172>Lorem Ipsum";
Lets say I want the data that is in-between the two characters '<' & '>'
So the result should be "172"
Now, if the string was going to be 3 digits inbetween these every time, using a sub-string would be fine, however that's not the case, as this string will be changing, so lets say this string could be
String test = "<9>Lorem Ipsum"
I would need the result to be "9"
How should I go about getting this information.
The code will be the following:
String test = "<172>Lorem Ipsum";
int index1 = test.indexOf('<');
int index2 = test.indexOf('>', index1);
String result = test.substring(index1 + 1, index2);
System.out.println("result = " + result);
And the result:
result = 172
String data = test.substring(test.indexOf("<")+1,test.indexOf(">"));
You can use regexp to get the data you need.
Something like this maybe
Pattern p = Pattern.compile("^<(\\d+)>");
Matcher m = p.matcher("<172>Lorem Ipsum");
if (m.find())
System.out.println(m.group(1));
else
System.out.println("your string doesn't start with \"<digits>\"");
In fact for this you can also try using replaceAll with a regex.
System.out.println("<172>Lorem Ipsum".replaceAll(".*<|>.*", ""));
Try something like this:
public Test() {
String test = "<172>Lorem Ipsum";
String number = "";
if (test.startsWith("<")) {
for (int index = 1 ; index < test.length() ; index++) {
if (!test.substring(index, index+1).equals(">")) {
number += test.substring(index, index+1);
} else {
break;
}
}
}
System.out.println(number);
}
int leftBound = data.indexOf("<");
int rightBound = data.indexOf(">");
data.substring(leftBound+1, rightBound));
Figured it out. It was one of those "Ask" then instantly figure it out things.

Categories

Resources