This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
i have array which is:
String[] array= {azem, 1 , soaib, 3}; // a[0]= azem , a[1]= 1, a[2]=soaib, a[3]= 3
My code is not printing any thing. I also saw ascii table and get the values of numbers in string that is from 48 to 57 but no printing.
Mycode:
String input = "1"; // integers as input
//String takeinput;
// String input = "48" + takeinput;
for(int i=0; i<array.length; i++){
if(array[i]== input){
System.out.print(array[i-1]);
System.out.print(array[i]);
}
In Java, the == compares if the two references point to the same object in memory, not whether they actually point to equivalent strings.
Use array[i].equals(input) instead.
This,
String[] array= {"azem", "1" , "soaib", "3"}; // a[0]= azem , a[1]= 1, a[2]=soaib, a[3]= 3
String input = "1"; // integers as input
//String takeinput;
// String input = "48" + takeinput;
for(int i=0; i < array.length; i++){
if(array[i].equals(input)) { // Modified
System.out.print(array[i-1]);
System.out.print(array[i]);
}
Or better, if you know every odd position (indexed 0) would be number, you can rewrite the code as,
int input = 1; // Modified : integers as input
for(int i=1; i < array.length; i += 2){
if(Integer.valueOf(array[i]) == input) { // Modified
System.out.println(array[i-1] + ":" + array[i]);
}
This would be a cleaner and a faster solution.
Did you try Integer.parseInt(...) while comparing strings with numeric values?
Integer.parseInt("26") == Integer.parseInt("56")
Update
You can also try comparing strings with .equals() method, as below.
array[i].equals(input);
Also, use println() instead of print() to be sure of what is printing.
Shishir
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Asked in JP Morgan:
You are given a string containing jumbled letters from several concatenated words. Each word is a numeral from zero to nine. Each numeral may be used multiple times in the jumbled string.
Write a program that returns integers corresponding to the numerals used to form the jumbled string. Integers must be sorted in ascending order.
For example, reuonnoinfe are shuffled letters of the strings one four nine. Your program's output should be 149.
Input:
A string formed from jumbled letters of numerals. For example:
reuonnoinfe
Output:
A sequence of integers used to form the string in ascending order. For example:
149
I tried solving but could not solve it. Below is my solution but it's not working. It will be great if someone can provide a solution in java.
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
String line = "reuonnoinfe";
String constNum = "zero,one,two,three,four,five,six,seven,eight,nine";
List<String> subStringList = subString(line, line.length());
System.out.println(calculateNumber(constNum, subStringList));
}
// To find all the substring from given string with length > 3 and <6
private static List<String> subString(String str, int n) {
List<String> retString = new ArrayList<>();
String tempStr;
// Pick starting point
for (int i = 0; i < n; i++) {
// Pick ending point
for (int j = i + 1; j <= n; j++) {
// Print characters from current
// starting point to current ending
// point.
tempStr = str.substring(i, j);
if (null != tempStr && tempStr.length() > 2 && tempStr.length() < 4) {
retString.add(tempStr.toLowerCase());
}
}
}
return retString;
}
// find all the substring which are anagrams of one the number String.
private static String calculateNumber(String stringConst, List<String> subStringList) {
StringBuilder strb = new StringBuilder();
stringConst = "one";
String[] str = stringConst.split(",");
int cnt = 0;
for (String obj : str) {
for (String objSubString : subStringList) {
if (areAnagram(obj.toCharArray(), objSubString.toCharArray())) {
strb.append(cnt + "");
}
}
cnt++;
}
return strb.toString();
}
// find two string are angram
private static boolean areAnagram(char str1[], char str2[]) {
int NO_OF_CHARS = 256;
// Create 2 count arrays and initialize
// all values as 0
int count1[] = new int[NO_OF_CHARS];
Arrays.fill(count1, 0);
int count2[] = new int[NO_OF_CHARS];
Arrays.fill(count2, 0);
int i;
// For each character in input strings,
// increment count in the corresponding
// count array
for (i = 0; i < str1.length && i < str2.length; i++) {
count1[str1[i]]++;
count2[str2[i]]++;
}
// If both strings are of different length.
// Removing this condition will make the program
// fail for strings like "aaca" and "aca"
if (str1.length != str2.length)
return false;
// Compare count arrays
for (i = 0; i < NO_OF_CHARS; i++)
if (count1[i] != count2[i])
return false;
return true;
}
}
Seems you know how to create array with char occurence count (count1, count2) - this is key for counting approach.
Edit the first try suffers from "breaking" combination(s) ("one" steals chars from "four + seven" etc) as Ole V.V. noticed
If we have no excessive chars, we can traverse sample array is special order: at first even indices (all these words contain unique chars like "z" in "zero"), then odd ones, and finally sort result (or generate two separate strings and merge them)
Pseudocode outline:
create array or list of sample strings A[0] = "zero" etc
create char count array for string "reuonnoinfe" c1
for (int i = 0; i < 10; i += 2)
create char count array c2 for A[i]
while ALL non-zero elements of c2 are <= than corresponding c1 elements:
add i (index!) to output
decrement c1[] by c2[]
// we can stop here if c1 becomes all-zero
for (int i = 1; i < 10; i += 2)
create char count array c2 for A[i]
while ALL non-zero elements of c2 are <= than corresponding c1 elements:
add i (index!) to output
decrement c1[] by c2[]
sort output
Some examples of output (quick-made Delphi code ideone):
eightnineoneonefoureightsixfivesevenseven
otfoenfueeseiiivsngrenthnevhxineogeneiesv
1145677889
onethreeseven
eeetnhvreones
137
eighttwozerosixfourninesixninesevensix
evhionfxietnnnozgieeourwxrsetsiisxnesi
0246667899
twosixtwoninesevenfoureightninezerosix
onfsntweeieitsixegxtozhinnersonvrwuioe
0224667899
zerofouronefoureightninefiveseven
srnfneriouiheeeovurevtifeofngneoz
01445789
threethreefivesevenonezerofoureightfour
tunorheeierthorgvoeeuzeffnerfreeveoihts
013344578
fiveonezeroseventhreesevenfoureight
netoseeeefrieotnernorfheugevseizvvh
01345778
fiveseventwo
fnewtveeosvi
257
This question already has answers here:
Split string to equal length substrings in Java
(23 answers)
Closed 5 years ago.
String str = "abcdefghijklmnoprqstuvwxyz";
String[] array = new String[str.length()/4 +1];
Array should look like array = {"abcd","efgh","ijkl"...."yz"} after my work.
Here is what I have tried:
WORK1:
int strIndex = 0;
int arrayIndex=0;
for(strIndex=0; strIndex<str.length();strIndex++) {
array[arrayIndex] += Character.toString(str.charAt(strIndex));
if((strIndex % 4 == 0) && (strIndex != 0 ))
arrayIndex++;
}
========================================================================
WORK2:
String str = "abcdefghijklmnoprqstuvwxyz";
String[] array = new String[str.length()/4 +1];
int start = 0; // 0->4->8->12..
int end = 4; // 4->8->12->16...
System.out.println("arraylength:"+array.length);
for(int i=0;i<array.length;i++) {
array[i] = str.substring(start,end);
start+=4;
end+=4;
}
===========================================
WORK1: it gives me the output of abcde fghi jklm nopr qstu vwxy z, which is wrong
WORK2: Because substring() jumps by 4, it will be the cause of Exception when it access the index of 28. Last part should be: (str.substring(24,26));, I can't think of efficient way to handle this.
Any advice will be appreciated.
You Need to restrict the Substring end to the strings Maximum lenght:
// pseudocode - you did not supply a tag for the language you are using
str.Substring(start,Math.Min(str.Count,end)) // Math.Min == C#
WORK1 should work with a minor change.
Currently you're putting "abcde" into the first array element simply because you're adding the 0th, 1st, 2nd, 3rd and 4th elements. You want to seperate before the 4th element not after. Give this a try:
int strIndex = 0;
int arrayIndex=0;
for(strIndex=0; strIndex<str.length();strIndex++) {
if((strIndex % 4 == 0) && (strIndex != 0 ))
arrayIndex++;
array[arrayIndex] += Character.toString(str.charAt(strIndex));
}
Hopefully this helps. Let me know how you get on!
Check the below code sniplet, it works fine as you said.
Let me know if any issues. (Added a syso just to validate the answer :) )
String str = "abcdefghijklmnoprqstuvwxyz";
String[] array = new String[str.length()/4 +1];
int start = 0; // 0->4->8->12..
int end = 4; // 4->8->12->16...
int length = str.length();
System.out.println("arraylength:"+array.length);
for(int i=0;i<array.length;i++) {
array[i] = str.substring(start,end);
start+=4;
end+=4;
System.out.println(array[i]);
if(end>length)
end=length;
}
This question already has answers here:
Remove last character of a StringBuilder?
(17 answers)
Closed 6 years ago.
I've searched hours for this kind of problem, but I've got no luck.
In Java, I'm try to get this kind of output:
1, 2, 3
(without the use of StringBuilder)
The result I am getting is:
1, 2, 3,
with the code:
for(int i=1; i <= 3; i++){
String output = "";
output += i + ", ";
System.out.print(output);
}
p.s I am not using any arrays for my code.
From Java 8+, this can be achieved using join method.
String.join(",", list)
be careful where you make the final print as you have an accumulator string variable that will serve to make the impression at the end
in addition also consider where you declare your variables within the variable will be created for the few times iterate the for, preferably testify before the cycle
use substring takes two parameters start position, end position
String output = "";
for(int i=1; i <= 3; i++){
output += i + ", ";
}
System.out.print(output.substring(0, output.length()-2));
//obtains from 1, 2.3 and omit the, end with the length () - 1 as the final //position
ouput
1, 2, 3
Here is one variation which has only a single ternary expression in the loop to build the output you want.
String output = "";
for (int i=1; i <= 3; i++) {
output += (i > 1) ? ", " + i : i;
}
System.out.print(output);
Though there may be many possible ways to doing this, but the one that I like most is where you don't introduce any unnecessary comparisons within the for loop.
So what you can do is for the first character only, you can directly put it in the string outside the loop, and for all the others, you can append ", <number>" with the original string.
String output = "1";
for(int i=2; i <= 3; i++){
output += ", " + i;
}
System.out.print(output);
Easy:
String output = "1";
for(int i=2; i <= 3; i++){
output += ", " + i;
}
System.out.print(output)
That'll give you
1, 2, 3
No need to complicate the task. This kind of thing comes up all the time. Just treat the first case as a special case.
Try this it is more easier, just check string length and if something in variable append separator:
String output = "";
for(int i=1; i <= 3; i++){
if(output .length>0)
{
output +=',';
}
output += i;
System.out.print(output);
}
Code snippet for JQuery:
var output = "";
for(var i=1; i <= 3; i++){
if(output .length>0)
{
output +=',';
}
output += i;
console.log(output);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can do it simply using java 8 stream api
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
String s = list.stream().map(i -> i.toString ()).collect(Collectors.joining(","));
This question already has answers here:
Java: parse int value from a char
(9 answers)
Closed 6 years ago.
I accepted a number as string in java as S=1234 .NOW i want to get the integer values at s[0] s[1] s[2] s[3] .
for(int i=0;i<l;i++)// l is length of string s
int x=s[i]-'0';// print this now
but this doesn't seem to work.
Java strings aren't just char arrays, they're objects, so you cannot use the [] operator. You do have the right idea, though, you're just accessing the characters the wrong way. Instead, you could use the charAt method:
for(int i = 0; i < l; i++) { // l is length of string s
int x = s.charAt(i) - '0';
// Do something interesting with x
}
You can get the integer by using charAt() in combination of getting the numeric value of that Character.
// Assuming you already have the Integer object "S" declared and assigned
int[] s = new int[Integer.toString(S).length()]; // create the integer array
for(int i = 0; i < Integer.toString(S).length(); i++)
{
int x = Character.getNumericValue(S.charAt(i));
s[i] = x;
}
Got this information from another stack overflow response: Java: parse int value from a char
int x = Character.getNumericValue(S.charAt(i));
You can convert an numerical string just by using Character.getNumericalValue() method. below is the way to get it.
String num = "1234";
char[] a=num.toCharArray();
ArrayList<Integer> p = new ArrayList<>();
for(int i=0; i<a.length; i++){
p.add(Character.getNumericValue(a[i]));
System.out.println(p.get(i));
}
Hi i got the following code which i use to get some integers from a string. I am separating successfully the negative and positive integers by combining the string with the next number if the char at the index is "-" and i can put the numbers in an integer array...
//degree is the String i parse
String together="";
int[] info=new int[degree.length()];
int counter=0;
for (int i1 = 0; i1 < degree.length(); i1++) {
if (Character.isSpace(degree.charAt(i1))==false){
if (Character.toString(degree.charAt(i1)).equalsIgnoreCase("-")){
together="-";
i1++;
}
together = together + Character.toString(degree.charAt(i1));
info[counter]=Integer.parseInt(together);
}
else if (Character.isSpace(degree.charAt(i1))==true){
together ="";
counter++;
}
But i go this strange problem....the string looks exactly like "4 -4 90 70 40 20 0 -12" and the code parses and puts the integers into the array only to the "0" number i mean i get all the number negatives and positives into my array except the last "-12" number... any ideas?
I think there's a much simpler solution to your problem:
// First split the input String into an array,
// each element containing a String to be parse as an int
String[] intsToParse = degree.split(" ");
int[] info = new int[intsToParse.length];
// Now just parse each part in turn
for (int i = 0; i < info.length; i++)
{
info[i] = Integer.parseInt(intsToParse[i]);
}