Reverse a string without use of library function in java - java

I am new to programming I need to reverse a string without using the library function.
I am able to reverse but as expected.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
String rev = "";
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<String> splitResult = new ArrayList<String>();
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == ' ')
list.add(i);
list.add(0, 0);
list.add(list.size(), s.length());
String[] words = new String[list.size()];
for (int j = 0; j <= words.length - 2; j++)
splitResult.add(s.substring(list.get(j), list.get(j + 1)).trim());
System.out.println(splitResult);
String[] str = new String[splitResult.size()];
str = splitResult.toArray(str);
for (int i = 0; i < str.length; i++) {
if (i == str.length - 1) {
rev = str[i] + rev;
} else {
rev = " " + str[i] + rev;
}
}
System.out.println(rev);
Expected:
Input: i am coder
output: redoc ma i
actual
input: i am coder
output: coder am i

You can just provide an empty result variable, iterate the characters of the given String by using an enhanced for-loop (also known as for-each loop) setting every character to index 0 of the result variable by just concatenating the character to the result variable like this:
public static void main(String[] args) {
// input
String s = "I am coder";
// result variable for reverse input
String reverseS = "";
// go through every single character of the input
for (char c : s.toCharArray()) {
// and concatenate it and the result variable
reverseS = c + reverseS;
}
// then print the result
System.out.println(reverseS);
}
You can of course do that in a slightly different way using a classic for-loop and the length of the input, see this example:
public static void main(String[] args) {
String s = "I am coder";
String reverseS = "";
for (int i = 0; i < s.length(); i++) {
reverseS = s.charAt(i) + reverseS;
}
System.out.println(reverseS);
}

String s = "I am coder";
String rev="";
for (int i = s.length()-1; i >=0; i--) {
rev+=s.charAt(i);
}
System.out.println(rev);
I have set the index I to the last character of the given string and the condition is set to 0(i.e the first character). Hence the loop runs from the last character to the first character. It extracts each of the characters to a given new String. Hope it helps!

You can just take another list go from last to first and display like this
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
ArrayList<Character> working = new ArrayList<Character>();
ArrayList<Character> finished = new ArrayList<Character>();
for (char ch: s.toCharArray()) {
working.add(ch);
}
for(int i = working.size() - 1 ; i>=0 ; i--){
finished.add(working.get(i));
}
for(int j = 0 ; j < finished.size() ; j++){
System.out.print(finished.get(j));
}

Related

How to reverse an array of characters that make up a sentence

I'm trying to figure out how to take a array of Characters that spell out a sentence backwards (or out of order) with the words separated by spaces to distinguish them and re-order them in the correct/reversed format so instead of the character array spelling out World Good Hello it would spell out Hello Good World like this ['H','e','l','l','o',' ','G','o','o','d',' ','W','o','r','l','d']
This is more or less a shot in the dark.
In the end I would like to return it back as an array of characters.
Code:
class Main {
public static void main(String[] args) {
// World Good Hello
// reverse to: Hello Good World
char[] chrArray = new char[] {'W','o','r','l','d',' ','G','o','o','d',' ','H','e','l','l','o'};
String str = String.valueOf(chrArray);
String[] strArray = str.split(" ");
char[] result = new char[0];
for (int i = 0; i < strArray.length; i++) {
for (int h = 0; h < strArray[i].length(); h++) {
char[] temp = new char[strArray[i].charAt(h)];
temp[temp.length - 1] = ' ';
char[] both = Arrays.copyOf(result, result.length);
List<character> temp2 = System.arraycopy(temp, 0, both, result.length, temp.length);
result = temp2.toCharArray();
}
}
}
}
public static String reverseWords(String sentence) {
String[] words = sentence.split("\\s+");
StringBuilder buf = new StringBuilder(sentence.length());
for (int i = words.length - 1; i >= 0; i--) {
if (buf.length() > 0)
buf.append(' ');
buf.append(words[i]);
}
return buf.toString();
}
Use reverseWords(...).toCharArray() to get char array.
I think the following code would be enough to reverse:
String[] strArray = str.split(" ");
for(int i =strArray.length-1;i>=0;i--) {
System.out.print(strArray[i] + " ");
}
this will output : Hello Good World

how to create a string from char array by adding char by char in java

How to create a String in Java by adding char by char.
I have to do it like this, because i have to add a "," between al letters.
I tried it like this, but it had not worked.
String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null;
for (int i = 0; i<l; i++){
a[i] = new Character(t.charAt(0));
}
for (int v = 0; v<l; v--){
ret += a[v];
ret += rel;
}
You don't need to do it so complicated, and you should explicitly use StringBuilder for such string operations:
String s = "abcdefg";
StringBuilder builder = new StringBuilder();
for (char c : s.toCharArray()) {
builder.append(c).append(",");
}
// Alternatively, you can do it in this way
for (String symbol : s.split("")) {
builder.append(symbol).append(",");
}
System.out.println(builder.toString());
// Java 8 (the result string doesn't have a comma at the end)
String collect = Arrays.stream(s.split("")).collect(Collectors.joining(","));
// Java8 StringJoiner
StringJoiner sj = new StringJoiner(",");
// StringJoiner sj = new StringJoiner(",", "", ",");
for (String str : s.split("")) {
sj.add(str);
}
If you use empty strings instead of null and initialize it then it works.
String t = "foobarbaz";
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = "";
for (int i = 0; i<l; i++){
a[i] = t.charAt(i);
}
for (int v = 0; v<l; v++){
ret += a[v];
ret += rel;
}
System.out.println(ret);
I've put the errors in your code in comments.
String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null; //you initialize ret to null, it should be "";
for (int i = 0; i<l; i++){
//you always set it to the character at position 0, you should do t.charAt(i)
//you don't need to use the wrapper class just t.charAt(i) will be fine.
a[i] = new Character(t.charAt(0));
}
for (int v = 0; v<l; v--){//you decrement v instead of incrementing it, this will lead to exceptions
ret += a[v];
ret += rel;//you always add the delimiter, note that this will lead to a trailing delimiter at the end
}
You might want to try a StringBuilder. It's a lot more efficient than using string concatenation. Using the array a is also not really necessary. Have a look at this implementation.
String t = "Test";
StringBuilder builder = new StringBuilder();
if(t.length() > 0){
builder.append(t.charAt(0));
for(int i=1;i<t.length();i++){
builder.append(",");
builder.append(t.charAt(i));
}
}
System.out.println(builder.toString());
Take a look at this:
//Word to be delimited by commas
String t = "ThisIsATest";
//get length of word.
int l = t.length(); //4
char[] a;
a = new char[l];
// we will set this to a comma below inside the loop
String rel = "";
//set ret to empty string instead of null otherwise the word "null" gets put at the front of your return string
String ret = "";
for (int i = 0; i<l; i++){
//you had 0 instead of 'i' as the parameter of t.charAt. You need to iterate through the elements of the string as well
a[i] = new Character(t.charAt(i));
}
for (int v = 0; v<l; v++){
/*set rel to empty string so that you can add it BEFORE the first element of the array and then afterwards change it to a comma
this prevents you from having an extra comma at the end of your list. */
ret += rel;
ret += a[v];
rel = ",";
}
System.out.println(ret);
String text = "mydata";
char[] arrayText = text.toCharArray();
char[] arrayNew = new char[arrayText.length*2];
for(int i = 0, j = 0; i < arrayText.length; i++, j+=2){
arrayNew[j] = arrayText[i];
arrayNew[j+1] = ',';
}
String stringArray = new String(arrayNew);
System.out.println(stringArray);
Results
m,y,d,a,t,a,

indexOf() returning -1 when looking for spaces

I'm using indexOf() to look for white spaces while trying to seperate words in a string but the index off keeps returning -1; Here's my code:-
import java.util.Scanner;
class Main {
public static void main(String[] args){
Scanner y = new Scanner(System.in);
System.out.println("Enter the String");
String s = y.nextLine();
int words = 1;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)==' ') words++;
}
String[] a = new String[words];
int l = s.length();
for (int i = 0; i <= words; i++) {
int r = s.indexOf(" ");
a[i] = s.substring(0, r);
s = s.substring((r + 1), l);
}
for(int i = 0; i <= words; i++) {
System.out.println(a[i]);
}
}
}
The problem is that you start words at 1 and increment it for each space you find. So if there's one space, words is 2. Then you're trying to look for that many spaces - but there's only 1, so when it runs out of spaces to find, it returns -1 and you get the exception.
You can just use String.split, e.g :
String s=y.nextLine();
for(String i : s.split(" ")) {
System.out.println(i);
}

Counting the number of each character in a file

I'm reading the contents of a text file char by char, then I've sorted them in ascending order and count the number of times each char occurs. When I run the program my numbers are way off, for example there are 7 'A' in the file, but I get 17. I'm thinking this means either something is wrong with my counting, or the way I'm reading the chars. Any ideas on what is wrong?
public class CharacterCounts {
public static void main(String[] args) throws IOException{
String fileName = args[0];
BufferedReader in = new BufferedReader(new FileReader(new File(fileName)));
ArrayList<Character> vals = new ArrayList<Character>();
ArrayList<Integer> valCounts = new ArrayList<Integer>();
while(in.read() != -1){
vals.add((char)in.read());
}
Collections.sort(vals);
//This counts how many times each char occures,
//resets count to 0 upon finding a new char.
int count = 0;
for(int i = 1; i < vals.size(); i++){
if(vals.get(i - 1) == vals.get(i)){
count++;
} else {
valCounts.add(count + 1);
count = 0;
}
}
//Removes duplicates from vals by moving from set then back to ArrayList
Set<Character> hs = new HashSet<Character>();
hs.addAll(vals);
vals.clear();
vals.addAll(hs);
//System.out.print(vals.size() + "," + valCounts.size());
for(int i = 0; i < vals.size(); i++){
//System.out.println(vals.get(i));
System.out.printf("'%c' %d\n", vals.get(i), valCounts.get(i));
}
}
}
When you write
if(vals.get(i - 1) == vals.get(i)){
Both are completely different references and they are not at all equals. You have to compare their value.
You want
if(vals.get(i - 1).equals(vals.get(i))){
I think you are overcomplicating your count logic. In addition you call read() twice in the loop so you are skipping every other value.
int[] counts = new int[256]; // for each byte value
int i;
while ((i = in.read()) != -1) { // Note you should only be calling read once for each value
counts[i]++;
}
System.out.println(counts['a']);
Why not use regex instead, the code will be more flexible and simple. Have a look at the code below:
...
final BufferedReader reader = new BufferedReader(new FileReader(filename));
final StringBuilder contents = new StringBuilder();
//read content in a string builder
while(reader.ready()) {
contents.append(reader.readLine());
}
reader.close();
Map<Character,Integer> report = new TreeMap<>();
//init a counter
int count = 0;
//Iterate the chars from 'a' to 'z'
for(char a = 'a';a <'z'; a++ ){
String c = Character.toString(a);
//skip not printable char
if(c.matches("\\W"))
continue;
String C = c.toUpperCase();
//match uppercase and lowercase char
Pattern pattern = Pattern.compile("[" + c + C +"]", Pattern.MULTILINE);
Matcher m = pattern.matcher(contents.toString());
while(m.find()){
count++;
}
if(count>0){
report.put(a, count);
}
//reset the counter
count=0;
}
System.out.println(report);
...

Java - make new string based on old one and lag

I need to get a new string based on an old one and a lag. Basically, I have a string with the alphabet (s = "abc...xyz") and based on a lag (i.e. 3), the new string should replace the characters in a string I type with the character placed some positions forward (lag). If, let's say, I type "cde" as my string, the output should be "fgh". If any other character is added in the string (apart from space - " "), it should be removed. Here is what I tried, but it doesn't work :
String code = "abcdefghijklmnopqrstuvwxyzabcd"; //my lag is 4 and I added the first 4 characters to
char old; //avoid OutOfRange issues
char nou;
for (int i = 0; i < code.length() - lag; ++i)
{
old = code.charAt(i);
//System.out.print(old + " ");
nou = code.charAt(i + lag);
//System.out.println(nou + " ");
// if (s.indexOf(old) != 0)
// {
s = s.replace(old, nou);
// }
}
I commented the outputs for old and nou (new, but is reserved word) because I have used them only to test if the code from position i to i + lag is working (and it is), but if I uncomment the if statement, it doesn't do anything and I leave it like this, it keeps executing the instructions inside the for statmement for code.length() times, but my string doesn't need to be so long. I have also tried to make the for statement like below, but I got lost.
for (int i = 0; i < s.length(); ++i)
{
....
}
Could you help me with this? Or maybe some advices about how I should think the algorithm?
Thanks!
It doesn't work because, as the javadoc of replace() says:
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
(emphasis mine)
So, the first time you meet an 'a' in the string, you replace all the 'a's by 'd'. But then you go to the next char, and if it's a 'd' that was an 'a' before, you replace it once again, etc. etc.
You shouldn't use replace() at all. Instead, you should simply build a new string, using a StringBuilder, by appending each shifted character of the original string:
String dictionary = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
char oldChar = input.charAt(i);
int oldCharPositionInDictionary = dictionary.indexOf(oldChar);
if (oldCharPositionInDictionary >= 0) {
int newCharPositionInDictionary =
(oldCharPositionInDictionary + lag) % dictionary.length();
sb.append(dictionary.charAt(newCharPositionInDictionary));
}
else if (oldChar == ' ') {
sb.append(' ');
}
}
String result = sb.toString();
Try this:
Convert the string to char array.
iterate over each char array and change the char by adding lag
create new String just once (instead of loop) with new String passing char array.
String code = "abcdefghijklmnopqrstuvwxyzabcd";
String s = "abcdef";
char[] ch = s.toCharArray();
char[] codes = code.toCharArray();
for (int i = 0; i < ch.length; ++i)
{
ch[i] = codes[ch[i] - 'a' + 3];
}
String str = new String(ch);
System.out.println(str);
}
My answer is something like this.
It returns one more index to every character.
It reverses every String.
Have a good day!
package org.owls.sof;
import java.util.Scanner;
public class Main {
private static final String CODE = "abcdefghijklmnopqrstuvwxyz"; //my lag is 4 and I added the first 4 characters to
#SuppressWarnings("resource")
public static void main(String[] args) {
System.out.print("insert alphabet >> ");
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
char[] char_arr = s.toCharArray();
for(int i = 0; i < char_arr.length; i++){
int order = CODE.indexOf(char_arr[i]) + 1;
if(order%CODE.length() == 0){
char_arr[i] = CODE.charAt(0);
}else{
char_arr[i] = CODE.charAt(order);
}
}
System.out.println(new String(char_arr));
//reverse
System.out.println(reverse(new String(char_arr)));
}
private static String reverse (String str) {
char[] char_arr = str.toCharArray();
for(int i = 0; i < char_arr.length/2; i++){
char tmp = char_arr[i];
char_arr[i] = char_arr[char_arr.length - i - 1];
char_arr[char_arr.length - i - 1] = tmp;
}
return new String(char_arr);
}
}
String alpha = "abcdefghijklmnopqrstuvwxyzabcd"; // alphabet
int N = alpha.length();
int lag = 3; // shift value
String s = "cde"; // input
StringBuilder sb = new StringBuilder();
for (int i = 0, index; i < s.length(); i++) {
index = s.charAt(i) - 'a';
sb.append(alpha.charAt((index + lag) % N));
}
String op = sb.toString(); // output

Categories

Resources