Reverse Char Array [duplicate] - java

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)

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

Write a program that returns integers corresponding to the numerals used to form the jumbled string. Integers must be sorted in ascending order [closed]

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

Spliting the string by number of chars [duplicate]

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

Can't spot the null exception in program [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I want to pick a particular “short” word in an array of words, that is, words with at most three characters.
For this example, if you are passed an array containing the strings
"Mary", "had", "a", "little", "lamb"
and you are asked to return the second short word, you would return "a".
import java.util.*;
public class Numbers
{
String[] words = {"Mary", "had" , "a" , "little" , "lamb"};
int n = 2;
public String Numbers;
String[] word;
{
int counter = 1;
int length = 0;
int count = 0;
for (int i = 0; i < words.length; i++)
{
length = words[i].length();
if (length <= 3)
{
count++;
**word[count] = words[i];**
}
}
String answer = word[n];
System.out.println(answer);
}
}
When I run the code, it gives me a null exception error, and I'm not sure how to fix it. The debugger told me it had to do something with the
word[count] = words[i];
What is wrong with my code?
The array needs to init.
String[] word = new String[10];

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

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

Categories