Is it possible in Java to efficiently read an integer from random position of the string? For instance, I have a
String s = "(34";
if (s.charAt(0) == '(')
{
// How to read a number from position = 1 to the end of the string?
// Of course, I can do something like
String s1 = s.substring(1);
int val = Integer.parseInt(s1);
}
but it dynamically creates a new instance of string and seems to be too slow and performance hitting.
UPDATE
Well, to be precise: I have an array of strings in form "(ddd" where d is a digit. So I do know that a number starts always from pos = 1. How do I efficently read these numbers?
Integer.parseInt(s1.replaceAll("[\\D]", ""))
Answered before the update:
I'm not an expert in regex, but hope this "\\d+" is useful to you. Invoke the below method with pattern: "\\d+".
public static int returnInt(String pattern,String inputString){
Pattern intPattern = Pattern.compile(pattern);
Matcher matcher = intPattern.matcher(inputString);
matcher.find();
String input = matcher.group();
return Integer.parseInt(input);
}
Answered after the update:
String is a final object, you cannot edit it, so if you want to get some digit value from it, you have the 2 ways:
1. Use your code, that will work fine, but if you care about performance, try 2nd way.
2. Divide your string on digits and add them to get the result:
public static void main(String[] args) {
String input = "(123456";
if(input.charAt(0) == '(') {
System.out.println(getDigit(input));
}
}
private static int getDigit(String s) {
int result = 0;
int increase = 10;
for(int i = 1; i < s.length(); i++) {
int digit = Character.getNumericValue(s.charAt(i));
result*=increase;
result += digit;
}
return result;
}
Output:
123456
If you don't want to allocate a new String then you can use the code in this other SO answer:
int charArrayToInt(char[] data, int start, int end) throws NumberFormatException {
int result = 0;
for (int i = start; i < end; i++) {
int digit = ((int)data[i] & 0xF);
if ((digit < 0) || (digit > 9)) throw new NumberFormatException();
result *= 10;
result += digit;
}
return result;
}
You can call it with charArrayToInt(s.toCharArray(), 1, s.length())
Related
char [] text = {'H','e','l','L','o','H','e','l','L','o'};
char[] pat = {'H','e','?','l','o'}; //'?' stands for every possible sign
We can ignore if the letters are upper or lower case.
Now I need to output how often it occurs.
Output: He?lo is in HelLoHelLo 2x
I know that you can use string methods like "contain" but how can I consider the question mark ?
public int matchCount(char[] text, char[] pattern) {
int consecCharHits = 0, matchCount = 0;
for (int i = 0; i < text.length; i++) {
if (text[i] == pattern[consecCharHits] || '?' == pattern[consecCharHits]) { // if char matches
consecCharHits++;
if (consecCharHits == pattern.length) { // if the whole pattern matches
matchCount++;
i -= consecCharHits - 1; // return to the next position to be evaluated
consecCharHits = 0; // reset consecutive char hits
}
} else {
i -= consecCharHits;
consecCharHits = 0;
}
}
return matchCount;
}
The way I would naively implement it without thinking too much about it
create inputIndex and set it to 0
create matchIndex and set it to 0
iterate over the input by incrementing the inputIndex one by one
compare the char in the input at inputIndex with the char in the match at matchIndex
if they "match" increment the matchIndex by one - if they don't set matchIndex to 0
if the matchIndex equals to your pat length increment the actual count of matches by one and set matchIndex back to 0
Where I wrote "match" you need to implement your custom match logic, ignoring the case and considering everything a match if the pattern at this place is a ?.
#Test
public void match() {
char [] text = {'H','e','l','L','o','H','e','l','L','o'};
char[] pat = {'H','e','?','l','o'}; //'?' stands for every possible sign
printMatch(text, pat);
}
private void printMatch(char[] text, char[] pat) {
String textStr = new String(text);
String patStr = new String(pat);
final String regexPattern = patStr.replace('?', '.').toLowerCase();
final Pattern pattern = Pattern.compile(regexPattern);
final Matcher matcher = pattern.matcher(textStr.toLowerCase());
while (matcher.find()) {
System.out.println(patStr + " is in " + textStr );
}
}
What about this ?
static int countPatternOccurences (char [] text, char [] pat)
{
int i = 0;
int j = 0;
int k = 0;
while ( i < text.length)
{
int a = Character.getNumericValue(pat[j]);
int b = Character.getNumericValue(text[i]);
if (a == b || pat[j] =='?')
{
j++;
}
else
{
j=0;
//return 0;
}
if(j == pat.length)
{
k++;
j = 0;
}
i++;
}
return k; // returns occurrences of pat in text
}
I am attempting to solve a problem where I create a method that counts the number of occurrences of capital and lowercase ("A" or "a") in a certain string. I have been working on this problem for a week now, and the main error that I am receiving is that "char cannot be dereferenced". Can anyone point me in the correct direction on this Java problem? Thank you.
class Main{
public static int countA (String s)
{
String s1 = "a";
String s2 = "A";
int count = 0;
for (int i = 0; i < s.length; i++){
String s3 = s.charAt(i);
if (s3.equals(s1) || s3.equals(s2)){
count += 1;
}
else{
System.out.print("");
}
}
}
//test case below (dont change):
public static void main(String[] args){
System.out.println(countA("aaA")); //3
System.out.println(countA("aaBBdf8k3AAadnklA")); //6
}
}
try a simpler solution
String in = "aaBBdf8k3AAadnklA";
String out = in.replace ("A", "").replace ("a", "");
int lenDiff = in.length () - out.length ();
Also as #chris mentions in his answer, the String could be converted to lowercase first and then only do a single check
the main error that I am receiving is that "char cannot be
dereferenced"
change this:
s.length // this syntax is incorrect
to this:
s.length() // this is how you invoke the length method on a string
also, change this:
String s3 = s.charAt(i); // you cannot assign a char type to string type
to this:
String s3 = Character.toString(s.charAt(i)); // convert the char to string
another solution to accomplishing your task in a simpler manner is by using the Stream#filter method. Then convert each String within the Stream to lowercase prior to comparison, if any Strings match "a" we keep it, if not we ignore it and at the end, we simply return the count.
public static int countA(String input)
{
return (int)Arrays.stream(input.split("")).filter(s -> s.toLowerCase().equals("a")).count();
}
For counting the number of time 'a' or 'A' appears in a String:
public int numberOfA(String s) {
s = s.toLowerCase();
int sum = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == 'a')
sum++;
}
return sum;
}
Or just replace everything else and see how long your string is:
int numberOfA = string.replaceAll("[^aA]", "").length();
To find the number of times character a and A appear in string.
int numA = string.replaceAll("[^aA]","").length();
So I'm creating a program that will output the first character of a string and then the first character of another string. Then the second character of the first string and the second character of the second string, and so on.
I created what is below, I was just wondering if there is an alternative to this using a loop or something rather than substring
public class Whatever
{
public static void main(String[] args)
{
System.out.println (interleave ("abcdefg", "1234"));
}
public static String interleave(String you, String me)
{
if (you.length() == 0) return me;
else if (me.length() == 0) return you;
return you.substring(0,1) + interleave(me, you.substring(1));
}
}
OUTPUT: a1b2c3d4efg
Well, if you really don't want to use substrings, you can use String's toCharArray() method, then you can use a StringBuilder to append the chars. With this you can loop through each of the array's indices.
Doing so, this would be the outcome:
public static String interleave(String you, String me) {
char[] a = you.toCharArray();
char[] b = me.toCharArray();
StringBuilder out = new StringBuilder();
int maxLength = Math.max(a.length, b.length);
for( int i = 0; i < maxLength; i++ ) {
if( i < a.length ) out.append(a[i]);
if( i < b.length ) out.append(b[i]);
}
return out.toString();
}
Your code is efficient enough as it is, though. This can be an alternative, if you really want to avoid substrings.
This is a loop implementation (not handling null value, just to show the logic):
public static String interleave(String you, String me) {
StringBuilder result = new StringBuilder();
for (int i = 0 ; i < Math.max(you.length(), me.length()) ; i++) {
if (i < you.length()) {
result.append(you.charAt(i)); }
if (i < me.length()) {
result.append(me.charAt(i));
}
}
return result.toString();
}
The solution I am proposing is based on the expected output - In your particular case consider using split method of String since you are interleaving by on character.
So do something like this,
String[] xs = "abcdefg".split("");
String[] ys = "1234".split("");
Now loop over the larger array and ensure interleave ensuring that you perform length checks on the smaller one before accessing.
To implement this as a loop you would have to maintain the position in and keep adding until one finishes then tack the rest on. Any larger sized strings should use a StringBuilder. Something like this (untested):
int i = 0;
String result = "";
while(i <= you.length() && i <= me.length())
{
result += you.charAt(i) + me.charAt(i);
i++;
}
if(i == you.length())
result += me.substring(i);
else
result += you.substring(i);
Improved (in some sense) #BenjaminBoutier answer.
StringBuilder is the most efficient way to concatenate Strings.
public static String interleave(String you, String me) {
StringBuilder result = new StringBuilder();
int min = Math.min(you.length(), me.length());
String longest = you.length() > me.length() ? you : me;
int i = 0;
while (i < min) { // mix characters
result.append(you.charAt(i));
result.append(me.charAt(i));
i++;
}
while (i < longest.length()) { // add the leading characters of longest
result.append(longest.charAt(i));
i++;
}
return result.toString();
}
How to best print 2 float numbers in scientific-notation but with same exponent?
eg: I'd like to print numbers like this:
1.234e-6
11.234e-6
And I would like some function to detect automatically best exponent - that is smaller number always start at first decimal digit and bigger number prints how it must with same exponent.
eg: 0.1 and 100 would print
1.000e-1
1000.000e-1
But even when I ask explicitly for 2 decimal places String.format("%2.3e",11.234e-6) I got 1.123e-5
So far I come up with code bellow. It works as I want. But as you can see it is not exactly short or swift... It would be great if someone would point to some Java native functions which helps me to do it more elegant...
public static String repeat(int count, String with) {
if(count<0){
return "";
}
if(count>1e5){
return "";
}
return new String(new char[count]).replace("\0", with);
}
public static String getFormattedDouble(double num,int posInt,int posFrac){
if(num == 0) return "0"; // correct 0 value to be print only with one 0
String sInt = repeat(posInt,"0");
String sFrac = repeat(posFrac,"0");
String sSing = num<0 ? "" : "+";
DecimalFormat form = new DecimalFormat(sSing+sInt+"."+sFrac+"E0");
String s = form.format(num);
s = s.replace("E","e"); // I really thing capital E looks ugly
return s;
}
public static String[] get2doublesSameExp(double a, double b){
String[] s = new String[2];
int expA;
if(a == 0) expA = 0;
else expA = (int)Math.floor(Math.log10(Math.abs(a)));
int expB;
if(b == 0) expB = 0;
else expB = (int)Math.floor(Math.log10(Math.abs(b)));
double expDif = Math.abs((double)expA-(double)expB);
int fractPos = 3;
if(expDif > 4) fractPos = 1; // too big exponent difference reduce fraction digits
if(expDif > 6){
// too big exponent difference print it normally it will be nicer
s[0] = String.format("%1.3e",a);
s[1] = String.format("%1.3e",b);
return s;
}
int minExp = Math.min(expA,expB) - 1;
s[0] = getFormattedDouble(a, expA - minExp, fractPos );
s[1] = getFormattedDouble(b, expB - minExp, fractPos );
// just text right justification
String rightJust = repeat((int)expDif," ");
int justIdx = expA < expB ? 0 : 1;
s[justIdx] = rightJust + s[justIdx];
return s;
}
String[] s = get2doublesSameExp(1.234e-6,11.234e-6);
I'm trying to get an int from a String. The String will always come as:
"mombojumbomombojumbomombojumbomombojumbomombojumbomombojumbohello=1?fdjaslkd;fdsjaflkdjfdklsa;fjdklsa;djsfklsa;dfjklds;afj=124214fdsamf=352"
The only constant in all of this, is that I will have a "hello=" followed by a number. With just that, I can't figure out how to pull out the number after the "hello=". This is what I have tried so far with no luck.
EDIT: The number will always be followed by a "?"
String[] tokens = s.split("hello=");
for (String t : tokens)
System.out.println(t);
I can't figure out how to isolate it from both sides of the int.
Pattern p = Pattern.compile("hello=(\\d+)");
Matcher m = p.matcher (s);
while (m.find())
System.out.println(m.group(1));
This sets up a search for anywhere in s that contains hello= followed by one or more digits (\\d+ means one or more digits). The loop looks for each occurrence of this pattern, and then whenever it finds a match, m.group(1) extracts the digits (since those are grouped in the pattern).
You should use a regular expression for this:
String str = "mombojumbomombojumbomombojumbomombojumbomombojumbomombojumbohello=1fdjaslkd;fdsjaflkdjfdklsa;fjdklsa;djsfklsa;dfjklds;afj=124214fdsamf=352";
Pattern p = Pattern.compile("hello=(\\d+)");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group(1)); // prints 1
}
Try this:
String r = null;
int col = s.indexOf("hello="); // find the starting column of the marker string
if (col >= 0) {
String s2 = s.substring(col + 6); // get digits and the rest (add length of marker)
col = 0;
// now find the end of the digits (assume no plus or comma or dot chars)
while (col < s2.length() && Character.isDigit(s2.charAt(col))) {
col++;
}
if (col > 0) {
r = s2.substring(0, col); // get the digits off the front
}
}
r will be the string you want or it will be null if no number was found.
Here is another non-regex performance approach. Wrapped in a method for your convenience
Helper method
public static Integer getIntegerForKey(String key, String s)
{
int startIndex = s.indexOf(key);
if (startIndex == -1)
return null;
startIndex += key.length();
int endIndex = startIndex;
int len = s.length();
while(endIndex < len && Character.isDigit(s.charAt(endIndex))) {
++endIndex;
}
if (endIndex > startIndex)
return new Integer(s.substring(startIndex, endIndex));
return null;
}
Usage
Integer result = getIntegerForKey("hello=", yourInputString);
if (result != null)
System.out.println(result);
else
System.out.println("Key-integer pair not found.");
Yet another non regex solution:
String str = "mombojumbomombojumbomombojumbomombojumbomombojumbomombojumbohello=142?fdjaslkd;fdsjaflkdjfdklsa;fjdklsa;djsfklsa;dfjklds;afj=124214fdsamf=352";
char arr[] = str.substring(str.indexOf("hello=")+6).toCharArray();
String buff ="";
int i=0;
while(Character.isDigit(arr[i])){
buff += arr[i++];
}
int result = Integer.parseInt(buff);
System.out.println(result);