Java convert string to int - java

I have a string. I split and store it as a char array . I am trying to convert it using Integer.parseInt and I get an error. How do I convert String to int?
Here's my code:
String tab[]= null;
tab=pesel.split("");
int temp=0;
for(String tab1 : tab)
{
temp=temp+3*Integer.parseInt(tab1); //error
}

Assuming you have a string of digits (e.g. "123"), you can use toCharArray() instead:
for (char c : pesel.toCharArray()) {
temp += 3 * (c - '0');
}
This avoids Integer.parseInt() altogether. If you want to ensure that each character is a digit, you can use Character.isDigit().
Your error is because str.split("") contains a leading empty string in the array:
System.out.println(Arrays.toString("123".split("")));
[, 1, 2, 3]
Now, there is a trick using negative lookaheads to avoid that:
System.out.println(Arrays.toString("123".split("(?!^)")));
[1, 2, 3]
Although, in any case, I would prefer the approach shown above.

You missed a gap in split method.
tab=pesel.split(" ");

Related

How to replace first and middle char in string

I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.

How to split string at operators

Im creating a calculator in Java.
If i have the user enter a string such as:
7+4-(18/3)/2
So far i have had to have the user enter a space between each number or operator.
How would i create an array from the given string where the string is split at either number or an operator so in this case the array would be:
[7, +, 4, -, (, 18, /, 3, ), /, 2]
(The array is of type String)
Any help would be really appreciated
Thanks :)
try this:
String[] temp = expression.split("[\s+-\\\(\)]+");
will split on:
white spaces
+ operator
- operator
\ character
( character
) character
You haven't specified what you want to do with the array. If you really want to evaluate the expression, then there are already libraries available for that. You can use one of them. But if you only want an array like the one you have shown, then also I wouldn't suggest to use regex. You can write your own parser method like below:
public static String[] parseExpression(String str) {
List<String> list = new ArrayList<String>();
StringBuilder currentDigits = new StringBuilder();
for (char ch: str.toCharArray()) {
if (Character.isDigit(ch)) {
currentDigits.append(ch);
} else {
if (currentDigits.length() > 0) {
list.add(currentDigits.toString());
currentDigits = new StringBuilder();
}
list.add(String.valueOf(ch));
}
}
if (currentDigits.length() > 0)
list.add(currentDigits.toString());
return list.toArray(new String[list.size()]);
}
Now call it like:
String str = "7+4-(18/3)/2";
System.out.println(Arrays.toString(parseExpression(str)));
and you will get your result.
The way I would do this is just scan the string myself to be honest. You will want to build an operation from the results anyway so you don't really gain anything by using an automated parser/splitter/etc.
Here is a rough sketch of the code:
List<Operations> ops = new ArrayList();
for (int i=0;i<str.length();i++) {
char c = str.get(i);
if (c == '.' || c >= '0' || c<='9') {
// extract a number, moving i onwards as I do
// insert number into ops (new Operation(num))
} else if (c!= ' ') {
Operator operator = operators.get(c);
if (operator == null) {
// Handle invalid input - could just skip it
} else {
// Add operator to ops
}
}
}
You would need to define operators for each of the various symbols.
Once you have done that you have parsed the string out to hold only the important data and compiled a list of what operations they are.
Now you need to work out how to process that list of operations applying correct precedence rules etc :) The simplest way may just be to repeatedly loop through the list each time performing each calculation that is valid that time around.
i.e.
1+2*(3+4)-(4+2)
First pass:
1+2*12-6
Second pass:
1+24-6
Result:
19
My first attempt was to use "\b", but that didn't split -(. After some searching, I came up with this:
(?<=[\(\)\+\-*\/\^A-Za-z])|(?=[\(\)\+\-*\/\^A-Za-z])
So, you will have to escape it and use it like this:
String input = ...;
String temp[] = input.split("(?<=[\\(\\)\\+\\-*\\/\\^A-Za-z])|(?=[\\(\\)\\+\\-*\\/\\^A-Za-z])");
System.out.println(Arrays.toString(temp));
Input:
7+4-(18/3)/2a^222+1ab
Output:
[7, +, 4, -, (, 18, /, 3, ), /, 2, a, ^, 222, +, 1, a, b]
See it in action here:
http://rubular.com/r/uHAObPwaln
http://ideone.com/GLFmo4

java split () method

I've got a string '123' (yes, it's a string in my program). Could anyone explain, when I use this method:
String[] str1Array = str2.split(" ");
Why I got str1Array[0]='123' rather than str1Array[0]=1?
str2 does not contain any spaces, therefore split copies the entire contents of str2 to the first index of str1Array.
You would have to do:
String str2 = "1 2 3";
String[] str1Array = str2.split(" ");
Alternatively, to find every character in str2 you could do:
for (char ch : str2.toCharArray()){
System.out.println(ch);
}
You could also assign it to the array in the loop.
str2.split("") ;
Try this:to split each character in a string .
Output:
[, 1, 2, 3]
but it will return an empty first value.
str2.split("(?!^)");
Output :
[1, 2, 3]
the regular expression that you pass to the split() should have a match in the string so that it will split the string in places where there is a match found in the string. Here you are passing " " which is not found in '123' hence there is no split happening.
Because there's no space in your String.
If you want single chars, try char[] characters = str2.toCharArray()
Simple...You are trying to split string by space and in your string "123", there is no space
This is because the split() method literally splits the string based on the characters given as a parameter.
We remove the splitting characters and form a new String every time we find the splitting characters.
String[] strs = "123".split(" ");
The String "123" does not have the character " " (space) and therefore cannot be split apart. So returned is just a single item in the array - { "123" }.
To do the "Split" you must use a delimiter, in this case insert a "," between each number
public static void main(String[] args) {
String[] list = "123456".replaceAll("(\\d)", ",$1").substring(1)
.split(",");
for (String string : list) {
System.out.println(string);
}
}
Try this:
String str = "123";
String res = str.split("");
will return the following result:
1,2,3

Is it possible to get only the first character of a String?

I have a for loop in Java.
for (Legform ld : data)
{
System.out.println(ld.getSymbol());
}
The output of the above for loop is
Pad
CaD
CaD
CaD
Now my question is it possible to get only the first characer of the string instead of the whole thing Pad or CaD
For example if it's Pad I need only the first letter, that is P
For example if it's CaD I need only the first letter, that is C
Is this possible?
Use ld.charAt(0). It will return the first char of the String.
With ld.substring(0, 1), you can get the first character as String.
String has a charAt method that returns the character at the specified position. Like arrays and Lists, String is 0-indexed, i.e. the first character is at index 0 and the last character is at index length() - 1.
So, assuming getSymbol() returns a String, to print the first character, you could do:
System.out.println(ld.getSymbol().charAt(0)); // char at index 0
The string has a substring method that returns the string at the specified position.
String name="123456789";
System.out.println(name.substring(0,1));
Here I am taking Mobile No From EditText It may start from +91 or 0 but i am getting actual 10 digits.
Hope this will help you.
String mob=edit_mobile.getText().toString();
if (mob.length() >= 10) {
if (mob.contains("+91")) {
mob= mob.substring(3, 13);
}
if (mob.substring(0, 1).contains("0")) {
mob= mob.substring(1, 11);
}
if (mob.contains("+")) {
mob= mob.replace("+", "");
}
mob= mob.substring(0, 10);
Log.i("mob", mob);
}
Answering for C++ 14,
Yes, you can get the first character of a string simply by the following code snippet.
string s = "Happynewyear";
cout << s[0];
if you want to store the first character in a separate string,
string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;
Java strings are simply an array of char. So, char c = s[0] where s is string.

problem with java split()

I have a string:
strArray= "-------9---------------";
I want to find 9 from the string. The string may be like this:
strArray= "---4-5-5-7-9---------------";
Now I want to find out only the digits from the string. I need the values 9,4, or such things and ignore the '-' . I tried the following:
strArray= strignId.split("-");
but it gets error, since there are multiple '-' and I don't get my output. So what function of java should be used?
My input and output should be as follows:
input="-------9---------------";
output="9";
input="---4-5-5-7-9---------------";
output="45579";
What should I do?
The + is a regex metacharacter of "one-or-more" repetition, so the pattern -+ is "one or more dash". This would allow you to use str.split("-+") instead, but you may get an empty string as first element.
If you just want to remove all -, then you can do str = str.replace("-", ""). This uses replace(CharSequence, CharSequence) method, which performs literal String replacement, i.e. not regex patterns.
If you want a String[] with each digit in its own element, then it's easiest to do in two steps: first remove all non-digits, then use zero-length assertion to split everywhere that's not the beginning of the string (?!^) (to prevent getting an empty string as a first element). If you want a char[], then you can just call String.toCharArray()
Lastly, if the string can be very long, it's better to use a java.util.regex.Matcher in a find() loop looking for a digit \d, or a java.util.Scanner with a delimiter \D*, i.e. a sequence (possibly empty) of non-digits. This will not give you an array, but you can use the loop to populate a List (see Effective Java 2nd Edition, Item 25: Prefer lists to arrays).
References
regular-expressions.info/Repetition with Star and Plus, Character Class, Lookaround
Snippets
Here are some examples to illustrate the above ideas:
System.out.println(java.util.Arrays.toString(
"---4--5-67--8-9---".split("-+")
));
// [, 4, 5, 67, 8, 9]
// note the empty string as first element
System.out.println(
"---4--5-67--8-9---".replace("-", "")
);
// 456789
System.out.println(java.util.Arrays.toString(
"abcdefg".toCharArray()
));
// [a, b, c, d, e, f, g]
The next example first deletes all non-digit \D, then splitting everywhere except the beginning of the string (?!^), to get a String[] each containing a digit:
System.out.println(java.util.Arrays.toString(
"#*#^$4#!#5ajs67>?<{8_(9SKJDH"
.replaceAll("\\D", "")
.split("(?!^)")
));
// [4, 5, 6, 7, 8, 9]
This uses a Scanner, with \D* as delimiter, to get each digit as its own token, using it to populate a List<String>:
List<String> digits = new ArrayList<String>();
String text = "(&*!##123ask45{P:L6";
Scanner sc = new Scanner(text).useDelimiter("\\D*");
while (sc.hasNext()) {
digits.add(sc.next());
}
System.out.println(digits);
// [1, 2, 3, 4, 5, 6]
Common problems with split()
Here are some common beginner problems when dealing with String.split:
Lesson #1: split takes a regular expression pattern
This is probably the most common beginner mistake:
System.out.println(java.util.Arrays.toString(
"one|two|three".split("|")
));
// [, o, n, e, |, t, w, o, |, t, h, r, e, e]
System.out.println(java.util.Arrays.toString(
"not.like.this".split(".")
));
// []
The problem here is that | and . are regex metacharacters, and since they are intended to be matched literally, they need to be escaped by preceding with a backslash, which as a Java string literal is "\\".
System.out.println(java.util.Arrays.toString(
"one|two|three".split("\\|")
));
// [one, two, three]
System.out.println(java.util.Arrays.toString(
"not.like.this".split("\\.")
));
// [not, like, this]
Lesson #2: split discards trailing empty strings by default
Sometimes it's desired to keep trailing empty strings (which are discarded by default split):
System.out.println(java.util.Arrays.toString(
"a;b;;d;;;g;;".split(";")
));
// [a, b, , d, , , g]
Note that there are slots for the "missing" values for c, e, f, but not for h and i. To fix this, you can use a negative limit argument to String.split(String regex, int limit).
System.out.println(java.util.Arrays.toString(
"a;b;;d;;;g;;".split(";", -1)
));
// [a, b, , d, , , g, , ]
You can also use a positive limit of n to apply the pattern at most n - 1 times (i.e. resulting in no more than n elements in the array).
Zero-width matching split examples
Here are more examples of splitting on zero-width matching constructs; this can be used to split a string but also keep "delimiters".
Simple sentence splitting, keeping punctuation marks:
String str = "Really?Wow!This.Is.Awesome!";
System.out.println(java.util.Arrays.toString(
str.split("(?<=[.!?])")
)); // prints "[Really?, Wow!, This., Is., Awesome!]"
Splitting a long string into fixed-length parts, using \G
String str = "012345678901234567890";
System.out.println(java.util.Arrays.toString(
str.split("(?<=\\G.{4})")
)); // prints "[0123, 4567, 8901, 2345, 6789, 0]"
Split before capital letters (except the first!)
System.out.println(java.util.Arrays.toString(
"OhMyGod".split("(?=(?!^)[A-Z])")
)); // prints "[Oh, My, God]"
A variety of examples is provided in related questions below.
References
regular-expressions.info/Lookarounds
Related questions
Can you use zero-width matching regex in String split?
"abc<def>ghi<x><x>" -> "abc", "<def>", "ghi", "<x>", "<x>"
How do I convert CamelCase into human-readable names in Java?
"AnXMLAndXSLT2.0Tool" -> "An XML And XSLT 2.0 Tool"
C# version: is there a elegant way to parse a word and add spaces before capital letters
Java split is eating my characters
Is there a way to split strings with String.split() and include the delimiters?
Regex split string but keep separators
You don't use split!
Split is to get the things BETWEEN the separator.
For this you want to eliminate the unwanted chars; '-'
The solution is simple
out=in.replaceAll("-","");
Use something like this to get the single values splitted. I'd rather eliminate the unwanted chars first to avoid getting empty/null String in the result array.
final Vector nodes = new Vector();
int index = original.indexOf(separator);
while (index >= 0) {
nodes.addElement(original.substring(0, index));
original = original.substring(index + separator.length());
index = original.indexOf(separator);
}
nodes.addElement(original);
final String[] result = new String[nodes.size()];
if (nodes.size() > 0) {
for (int loop = 0; loop smaller nodes.size(); loop++) {
result[loop] = (String) nodes.elementAt(loop);
}
}
return result;
}

Categories

Resources