extracting integer at each positions from a string S [duplicate] - java

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

Related

Why is .toCharArray() giving garbage value? [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 1 year ago.
Below mentioned code is for reversing k elements in a string of n size. Line 3 is returning garbage value. Can anyone please help me out on this.
class Solution{
public String reverseStr(String s, int k){
char[] ch = s.toCharArray();
Stack<Character> st = new Stack();
int i;
for(i = 0; i < k; i++){
st.push(ch[i]);
}
i = 0;
while(!st.isEmpty()){
ch[i] = st.pop();
}
return ch.toString();
}
}
Increment i
There is a mistake in this part of your code:
i = 0;
while(!st.isEmpty()){
ch[i] = st.pop();
}
Note that i remains 0 the whole time, so you are assigning to ch[0] in each iteration of the loop. You probably meant to increment i in the loop:
i = 0;
while(!st.isEmpty()){
ch[i++] = st.pop();
}
Generate String from char array
Note that the last line of your code:
return ch.toString();
will not return what you expect. If you want to convert the char array to a String containing the characters, do this instead:
return new String(ch);

the operator > is undefined for the argument type(s) java.lang.String, java.lang.String [duplicate]

This question already has answers here:
How can I compare two strings in java and define which of them is smaller than the other alphabetically?
(4 answers)
Closed 3 years ago.
at line 40:
if(stringArray[j] > stringArray[j+1])
it says the operator > is undefined for the argument types java.lang.String, java.lang.String. Why? and how do i fix it?
public static void main(String[] args)
{
System.out.println("Welcome! How many strings would you like to sort?");
Scanner input = new Scanner(System.in);
int stringSize = input.nextInt();
String [] array = new String[stringSize]; //creating array of the inputed size
for (int i = 0; i < stringSize; i++) //loop for iterating array
{
System.out.print("Please enter string " + (i+1) + ": ");
String stringInput = input.next(); //entering strings
array[i] = stringInput; //assigning to corresponding locations
}
int arrayLength = array.length;
sortLength(array, arrayLength);
System.out.print("Your sorted array is: ");
for (int i = 0; i < arrayLength; i++)
System.out.println(array[i] + ", ");
input.close();
System.out.print("Goodbye!");
}
public static void sortLength(String [] stringArray, int length) //sorting from shortest to longest using bubblesort method
{
length = stringArray.length;
for(int i = 0; i < length - 1; i++) //i represents # of items sorted
{
for(int j = 0; j < i; j++)
{
String temp = stringArray[i];
if(stringArray[j] > stringArray[j+1]) //comparing and swapping the array elements
{
temp = stringArray[j];
stringArray[j] = stringArray[j+1];
stringArray[j+1] = temp;
}
}
}
}
}
It says the operator > is undefined for the argument types java.lang.String, java.lang.String.
Correct
Why?
Because the relational operators >, >=, < and <= are only defined for primitive types. String is not a primitive type. It is a reference type.
(Aside: the == and != operators are defined for reference types, but you should not use them for comparing String values. Use String::equals for that. See How do I compare strings in Java?)
And how do i fix it?
It depends on what you are trying to do:
If you are trying to compare two String values lexically, use String::compareTo (javadoc)
If you are trying to compare two String values lexically ignoring lower / uppercase distinctions, use String::compareToIgnoreCase (javadoc).
If you are trying to order String objects by length, you will need to implement this by comparing values returned by String::length (javadoc). (You may want / need to use String::compareTo as a tie-breaker for when you have two strings that are the same length but not equal. Read your exercise's requirements carefully.)
You don't need to pass the length of the array in as an argument, and you should actually call String.length() to get (and compare by) the length(s) of your String(s). Also, don't just compare adjacent elements with j and j+1 (use i). Like,
public static void sortLength(String[] stringArray) {
for(int i = 1; i < stringArray.length; i++)
{
for(int j = 0; j < i; j++)
{
if(stringArray[j].length() > stringArray[i].length())
{
String temp = stringArray[j];
stringArray[j] = stringArray[i];
stringArray[i] = temp;
}
}
}
}

Reverse Char Array [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 5 years ago.
I am working on a code for homework where we have to use a char array holding a sentence and reverse the order of array so that the words are in opposite order in java for example "I am a house" should put out "house a am I" I am stuck on how to actually step through and order the array so the words go in this order any tips will help.
The code i have reverses the whole array but it does not put reverse it word by word
if(sentence.length%2 == 0)
{
int middleR = sentence.length/2;
int middleL = middleR - 1;
for(int i = middleR; i < sentence.length; i++)
{
char temp = sentence[i];
sentence[i] = sentence[middleL];
sentence[middleL] = temp;
middleL--;
}
}
else
{
int middle = sentence.length/2;
int end = sentence.length -1;
for(int i = 0; i < middle;i++)
{
char temp = sentence[i];
sentence[i] = sentence[end];
sentence[end] = temp;
end --;
}
}
Split the text into an array of Strings (String.split), put the array into a List (Arrays.asList), revers the list (Collections.reverse), get String array from the list (List.toArray)

How to store an integer variable as an input in character array in Java?

Convert aaabbcc string to a string a3b2c2.Here is there any way to store integer value 3 in a character array.Can I convert aaabbcc string into a string a3b2c2.
Integer data type requires 32 bit or 4 bytes space whereas character array contains blocks of 16 bits or 2 bytes space.
You might want to create an another integer array to hold your count values as this is not possible in the same character array directly.
There is a workaround of storing ASCII values of corresponding count values as characters in the same array but it might lead to ambiguity if there are numbers present as part of your original character array.
Hence I would suggest you use a separate integer array.
String str = "aaabbcc";
char c;
ArrayList<String>count=new ArrayList();
for(int i = 0; i < str.length(); i++){
if(!count.contains(str.charAt(i)+"")){
count.add(str.charAt(i)+"");
}
}
int [] dd = new int [count.size()];
for (int i = 0; i < str.length(); i++) {
c=str.charAt(i);
for(int j=0;j<count.size();j++){
if(count.get(j).equals(c+"")){
dd[j]++;
}
}
}
String newS="";
for(int i=0;i<count.size();i++){
newS+=count.get(i)+dd[i];
}
str = newS;
System.out.println(str);
you can do it using String, like you want to store 3 at 2nd position so do like this-
int n = 3;
String s = Integer.toString(n);
ch[1] = s.charAt(0); // ch[1] is representing 2nd position in aaabbc

how to compare numbers in string with string? [duplicate]

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

Categories