Reverse a string then swap every nth letter - java

I've been stuck on this problem for two hours now. Basically I need to reverse a string (which I've done no problem), then swap every nth letter (which is where im stuck).
Here is what I have so far:
public class StringMethods {
public static void main(String[] args) {
String s = "Hey there";
int n = 2;
System.out.println(reverseString(s));
System.out.println(reverseStringChallenge(s, n));
}
private static String reverseString(String s) {
String reversed = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i);
}
return reversed;
}
private static String reverseStringChallenge(String s, int n) {
String reversed = "";
String swapped = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i); // normal reverse
}
char [] charArray = reversed.toCharArray(); //Strings are immutable, convert string to char array
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0) {
//this is where im stuck
}
}
return swapped;
}
}
I know that strings are immutable in java so I need to convert the reversed string into a char array, and then loop through the array but not sure what to do here.
Any advice would be really appreciated. its doing my head in.
Edit: sorry what I mean by swap every nth letter is that say n = 2. then every second letter gets swapped with its previous one.

You didn't clarify the swap logic, but how about something like this:
for(int i = n; i < charArray.length; i += n) {
char a = charArray[i-n];
char b = charArray[n];
charArray[i-n] = b;
charArray[n] = a;
}

Here's a basic swap
int n = 1;
int n1 = 2;
int temp = n; // variable to hold n value
n = n2; // make n = n2
n2 = temp; // make n2 = n
// now n = 2
// and n2 = 1
Not really sure from your question what it is you're trying to do, so I can't really give a definite answer

If you are swapping the current char with the next char you could do something like:
private static String reverseStringChallenge(String s, int n)
{
String reversed = StringUitls.reverse(s);
StringBuilder sb = new StringBuilder();
char [] charArray = reversed.toCharArray();
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0)
{
sb.append(charArray[i+1]).append(charArray[i]);
i++;
}else{
sb.append(charArray[i]);
}
}
return sb.toString();
}
I'm excuse null and out of bound checks =) good luck

Related

How to get the first and last digits of a number and combine both

Example:
If i give a number 12345 , i should get an answer like 15243
in the same way if it is 123456 , i should get 162534
i have already tried getting the first value and appending the last value using reverse technique
public class MyFirstJavaProgram {
public static void main(String []args) {
String str = "12345";
String val = str;
char a;
int num=0;
int d=0;
int n;
for(int i=0; i<=str.length()/2; i++) {
a = str.charAt(i);
num = num*10+Character.getNumericValue(a);
if(Integer.parseInt(str)!=0){
d=Integer.parseInt(str)%10;
num = num*10+d;
n=Integer.parseInt(str)/10;
str = Integer.toString(n);
}
}
System.out.println(num);
}
}
i should get the result if they give even number or odd number
Without doing what is presumably homework for you, imagine you have a loop in which there are two integer variables a and b. Variables a and b are string indexes.
You are taking characters from the string at positions a,b,a,b,a,b etc.
BUT the values of a and b need to change for each iteration. If the length of the String is n, a will follow the sequence 0,1,2,3... and b will follow the sequence (n-1),(n-2),(n-3) etc
The loop should continue while a < b.
This is my solution for your exercise:
Method parameter "A" is Integer number you want to parse.
First you create Char Array from given number and then iterate through it. If i%2 == 0 it means that you take number from beginning otherwise from the end
public static int algorithm(int A) {
StringBuilder shuffleNumber = new StringBuilder();
char[] numbersArray = Integer.toString(A).toCharArray();
for (int i = 0; i < numbersArray.length; i++) {
if (i % 2 == 0)
shuffleNumber.append(numbersArray[i / 2]);
else
shuffleNumber.append(numbersArray[numbersArray.length - i / 2 - 1]);
}
return Integer.parseInt(shuffleNumber.toString());
}
If you want a solution without string methods, there is a not so complicated one:
public static void main(String[] args) throws IOException {
String str = "1234567";
int len = str.length();
int num=0;
char a;
for(int i = 0; i < len / 2; i++) {
a = str.charAt(i);
num = num * 10 + Character.getNumericValue(a);
a = str.charAt(len -1 - i);
num = num * 10 + Character.getNumericValue(a);
}
if (len % 2 == 1) {
a = str.charAt(str.length() / 2);
num = num * 10 + Character.getNumericValue(a);
}
System.out.println(num);
}
will print
1726354
Check the last if that takes care the case of odd number of digits in the number.
public class MyFirstJavaProgram {
public static void main(String []args) {
String str = "12345678";
int val = str.length();
char a;
int num=0;
int d=0;
int n;
for(int i=0; i<=str.length()-2; i++)
{
a = str.charAt(i);
num = num*10+Character.getNumericValue(a);
if(Integer.parseInt(str)!=0)
{
d=Integer.parseInt(str)%10;
num = num*10+d;
n=Integer.parseInt(str)/10;
str = Integer.toString( n );
}
}
if(val%2!=0)
{
num = num*10+Integer.parseInt(str)%10;
System.out.println(num);
}
else{System.out.println(num);}
}
}
this is working for my question... Thanks all
Following is my solution -
public static void solution(String s) {
StringBuffer st = new StringBuffer();
for (int i = 0; i < s.length() / 2; i++) {
st.append(s.charAt(i));
st.append(s.charAt(s.length() - 1 - i)); // appending characters from last
}
if (s.length() % 2 != 0) {
st.append(s.charAt(s.length() / 2));
}
System.out.println(Integer.parseInt(st.toString()));
}
my logic is to keep appending first and last character to new string till i < s.length/2.
If string is of odd length , it means only last character is remaining, append it to your resultant string.
Else , no character is left and you have your complete string.

Java Issue with String: Trying to reverse the midpoint of String.. String out of Range exception

I'm working on an assignment for one of my classes. I'm very new to java in general and for this problem I was asked to only use loops and the charAt(); command to reverse the midpoint of a string. However, I came to an issue when I try to reverse the string after the midpoint. It gave me an exception and I don't know how to make of it since it looks correct to me. Any help would be appreciated.
import java.util.Scanner;
public class PS4Reverse {
public static void main (String [] args) {
String x = "";
String t = "";
String full = "";
String rev = "";
String complete = "";
Scanner user = new Scanner(System.in);
System.out.println("Enter a string.");
x = user.nextLine();
int real = x.length();
int half = x.length();
half = half / 2;
int i = 0;
for (i = 0; i != half; i++)
{
char n = x.charAt(i);
full = full + n;
}
for (i = i; i != real; i++)
{
char n = x.charAt(i);
t = t + n;
}
int back = t.length();
System.out.println(back);
for (i = back; i != 0; i--)
{
char n = t.charAt(i);
rev = rev + n;
}
complete = full + rev;
System.out.println("Original String:\t\t" + x)
System.out.println("Reverse String:\t\t" + complete);
}
}
Thank all y'all very much in advance!
First of all, it helps if you're exact when telling us what exception is happening. It is a StringIndexOutOfBoundsException, not a String out of Range exception or an indexoutofrangeexception.
Anyway, this is the issue:
int back = t.length();
for (i = back; i != 0; i--)
{
char n = t.charAt(i);
The indexes are zero-baed, so if t.length() is 4, t.charAt(4) is going to be out of bounds. You need to start at t.length() - 1.
You got this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(Unknown Source)
at PS4Reverse.main(PS4Reverse.java:49)
int back = t.length(); // this code length of t string. But array indis is starting 0.
This means first item is 0 , last item must be back-1.
you use that;
for (i = back-1; i >= 0; i--)
{
char n = t.charAt(i);
rev = rev + n;
}

How to split a string into equal parts and store it in a string array

I'm fairly new to Java and am stuck on a particular homework question where a String gets passes and from there I have to split it into parts equal to an Integer that was passed.
For example: String "HelloWorld" is input and it has to be divided by 2 and those parts then have to be put into an array that has two parts like: array[hello, world].
Is there anyway to do this using a FOR loop?
My code so far enters the whole String into each array element. Here is my code:
String[] splitIntoParts(String word, int size) {
String[] array = new String[size];
for (int i = 0; i < array.length; i++) {
array[i] = word;
println(array[i]);;
}
return array;
}
There are many ways:
Here's the regex version:
public void splitEqual(String s){
int length = s.length();//Get string length
int whereToSplit;//store where will split
if(length%2==0) whereToSplit = length/2;//if length number is pair then it'll split equal
else whereToSplit = (length+1)/2;//else the first value will have one char more than the other
System.out.println(Arrays.toString(s.split("(?<=\\G.{"+whereToSplit+"})")));//split the string
}
\G is a zero-width assertion that matches the position where the previous match ended. If there was no previous match, it matches the beginning of the input, the same as \A. The enclosing lookbehind matches the position that's four characters along from the end of the last match.
Both lookbehind and \G are advanced regex features, not supported by all flavors. Furthermore, \G is not implemented consistently across the flavors that do support it. This trick will work (for example) in Java, Perl, .NET and JGSoft, but not in PHP (PCRE), Ruby 1.9+ or TextMate (both Oniguruma).
Using Substring:
/**
* Split String using substring, you'll have to tell where to split
* #param src String to split
* #param len where to split
* #return
*/
public static String[] split(String src, int len) {
String[] result = new String[(int)Math.ceil((double)src.length()/(double)len)];
for (int i=0; i<result.length; i++)
result[i] = src.substring(i*len, Math.min(src.length(), (i+1)*len));
return result;
}
You should also check this answer: Google Guava split
First check if the length of the string is a multiple of the divisor:
if(str.length() % divisor == 0)
Then you know that you can grab equal chunks of it. So you use substring to pull them out, in a loop.
while(str.length() > 0) {
String nextChunk = str.substring(0,divisor);
// store the chunk.
str = str.substring(divisor,str.length());
}
Will cycle through and grab a chunk that is divisor long each time.
Try the following application.It is dividing the provided word into equal parts based on the provided size per part
public class WordSpliter {
public static void main(String[] args) {
String[] words = new WordSpliter().splitter("abcdefghij", 4);
for(String s : words) System.out.println(s);
}
private String[] splitter(String word, int size) {
// Decide the size of the String array
int rest = word.length() % size;
int arrSize = ((word.length() - rest) / size) + 1;
// Declare the array and the start point of the word
String[] words = new String[arrSize];
int startPoint = 0;
for (int i = 0; i < words.length; i++) {
if (i + 1 == words.length) {
words[i] = word.substring(startPoint, startPoint + rest);
} else {
words[i] = word.substring(startPoint, startPoint + 4);
startPoint += 4;
}
}
return words;
}
}
Good Luck !!!!
You can use Brute force
public static List<String> splitStringEqually(String text, int size)
{
List<String> result = new ArrayList<String>((text.length() + size - 1) / size);
for (int i = 0; i < text.length(); i += size) {
result.add(text.substring(i, Math.min(text.length(), i + size)));
}
return result;
}
String s = "HelloWorld";
String firts_part=(String) s.subSequence(0, s.length() / 2);
String second_part=(String) s.subSequence((s.length() / 2)+1,s.length()-1 );
Try subSequence();
This is not plagarism, formatted the answer mentioned here - https://stackoverflow.com/a/3761521 as per the question.
public static void main(String[] args){
String str = "HelloWorld";
int parts = str.length()/3;
System.out.println(Arrays.toString(
str.split("(?<=\\G.{"+parts+"})")
));
}
Since length of a string is dived by 2
Code:
String st ="HelloWorld";
String firstPart = "";
String secondPart = "";
for (int j = 0; j < st.length(); j++) {
if ( j < st.length() /2) {
firstPart += st.charAt(j);
}else
secondPart += st.charAt(j);
}
System.out.println(firstPart);
System.out.println(secondPart);
Output:
Hello
World
Explanation: you add to firstPart String as long as your index has not met the middle index of the String. When it passed the middle index of String, you make the secondPart
Just looking at your input HelloWorld, You are trying to substring your input by Upper case letter.
You should go with that.
String str = "HelloWorldUser";
List<Integer> indexList = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
String temp = (str.charAt(i) + "").toUpperCase();
if (temp.equals(str.charAt(i) + "")) { // check for upper case letters
indexList.add(i);
}
}
List<String> subStrings = new LinkedList<>(); // to keep the insertion order
for (int i = indexList.size() - 1; i > -1; i--) { // substring reverse order
subStrings.add(str.substring(indexList.get(i)));
str=str.substring(0,indexList.get(i));
}
Collections.reverse(subStrings); // reverse to get original order
System.out.println(subStrings);
Out put:
[Hello, World, User]
If you want to get final result in to an array you can use
String[] arr= subStrings.toArray(new String[subStrings.size()]);
I figured it out. Here is my code:
String[] array = new String[size];
char[] charArray = new char[length(word)];
char[] temp = new char[length(word) / size];
int place = 0;
// turn the string into an array of chars
for (int i = 0; i < charArray.length; i++) {
charArray[i] = getChar(word, i);
}
// loop for each element of the desired string array
for (int i = 0; i < array.length; i++) {
// fill a temp array with the correct characters and the corect amount of characters
for (int j = 0; j < charArray.length / size; j++) {
temp[j] = charArray[place];
++place;
}
// insert the temp array into each element of the string array
array[i] = new String(temp);
}
return array;
A Simple solution is like
static void split(String str, int n) {
int partSize = str.length() / n;
while (str.length() - partSize > 0) {
String s = str.substring(0, partSize-1);
System.out.print(s + " ");
str = str.substring(partSize-1);
}
if (str.length() > 0) {
System.out.print(str);
}
}
You can do it using regex as follows:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 5)));
System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 4)));
System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 2)));
}
static String[] splitIntoParts(String word, int size) {
return word.replaceAll("(.{" + size + "})", "$1\n").split("\n");
}
}
Output:
[Hello, World]
[Hell, oWor, ld]
[He, ll, oW, or, ld]

Java: Creating a Delimiter Method that has Input/Output

I'm working on a study problem from class and essentially it reads a string, and a character. The character is the delimiter. It will then search the string for the delimiter and create an array in equal length to the number of times the delimiter is found. It then assigns each character or string to its own spot in the array and returns it.
Maybe I am over thinking things, but the just of it is to not rely on the various string methods and to sort of create your own. How can I get this method to only assign the string/char found in the one that is read to one position in the array and not all as well as stop it from adding unnecessary output? Help/Suggestions greatly appreciated
public static String[] explode(String s, char d){
String []c;
int count = 1;
//checks to see how many times the delimter appears in the string and creates an array of corresponding size
for(int i = 0; i < s.length(); i++){
if(d == s.charAt(i))
count ++;
}
c = new String [count];
//used for checking to make sure the correct number of elements are found
System.out.println(c.length);
//goes through the the input string "s" and checks to see if the delimiter is found
//when it is found it makes c[j] equal to what is found
//once it has cycled through the length of "s" and filled each element for c, it returns the array
for(int i = 0; i < s.length(); i++){
for(int j = 0; j < c.length; j++){
if(d == s.charAt(i))
c[j] += s.substring(i-1);
}
}
//provides output for the array [c] just to verify what was found
for(int y = 0; y < c.length; y++)
System.out.println(c[y]);
return c;
}
public static void main(String [] args){
String test = "a,b,c,d";
char key = ',';
explode(test,key);
}
^The following will output:
4
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
I'm aiming for:
4
a
b
c
d
Thank you
Perhaps you could try something like this:
public static void main(String[] args){
explode("a,b,c,d", ',');
}
public static void explode(final String string, final char delimiter){
int length = 1;
for(final char c : string.toCharArray())
if(delimiter == c)
length++;
if(length == 1)
return;
final String[] array = new String[length];
int index, prev = 0, i = 0;
while((index = string.indexOf(delimiter, prev)) > -1){
array[i++] = string.substring(prev, index);
prev = index+1;
}
array[i] = string.substring(prev);
System.out.println(length);
for(final String s : array)
System.out.println(s);
}
Output of the program above is:
4
a
b
c
d
Or if you want to utilize a List<String> instead (and Java 8), you could remove a couple of lines by doing something like this:
public static void explode(final String string, final char delimiter){
final List<String> list = new LinkedList<>();
int index, prev = 0;
while((index = string.indexOf(delimiter, prev)) > -1){
list.add(string.substring(prev, index));
prev = index+1;
}
list.add(string.substring(prev));
System.out.println(list.size());
list.forEach(System.out::println);
}

Swapping elements in ArrayList

I want to write a method, which takes a String and swaps each pair of characters in it and then concatenates them into a new String. Please let me know how to fix this code (or write a new better one):
static String s;
public static void proc(String w) {
ArrayList k = new ArrayList();
ArrayList m = new ArrayList();
System.out.println(w.length());
int j = 0;
//test arraylist to check if string is written into arraylist
for (int i = 0; i < w.length(); i++){
k.add(w.charAt(i));
}
String p = k.get(2).toString();
System.out.println(p);
//here starts the logic of my app
for (int n = 0; n < w.length(); n++){
String v = k.get(n).toString();
if (n == 0){
m.add(1, v);
}
else if (n == 1){
m.add(0, v);
}
else if ((n % 2) == 0){
m.add(n+1, v);
}
else {
m.add(n, v);
}
}
}
public static void main(String[] args){
s = "tests";
proc(s);
}
Hi this is not a homework, but am doing exercises from a book. Anyway using code provided by Jon managed to work on my own - it may be not as much elegant but is doing the job using dynamic sizing as well:
public static void proc(String w) {
ArrayList k = new ArrayList();
ArrayList g = new ArrayList();
String h = "";
for (int i = 0; i < w.length(); i++){
char temp = w.charAt(i);
k.add(i, temp);
}
for (int i = 0; i < w.length(); i++){
if (i == 0){
h = k.get(1).toString();
g.add(h);
}
else if (i == 1){
h = k.get(0).toString();
g.add(h);
}
else if ((i % 2) == 0){
h = k.get(i+1).toString();
g.add(h);
}
else if ((i % 2) == 1){
h = k.get(i-1).toString();
g.add(h);
}
}
System.out.println(g.toString());
}
public static void main(String[] args){
s = "test";
proc(s);
}
I haven't tried to go through exactly how your code is trying to work, but it looks unnecessarily complicated to me. Given that you don't need dynamic sizing, you can do this more easily with an array:
public static String swapPairs(String input) {
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length - 1; i += 2) {
char tmp = chars[i];
chars[i] = chars[i + 1];
chars[i + 1] = tmp;
}
return new String(chars);
}
Note that while this will work for "simple" characters (where each element of the array is independent of the rest), it doesn't try to take any form of "composite" characters into consideration, such as characters formed from two UTF-16 code units (surrogate pairs) or combined characters such as "e + acute accent". Doing this sort of contextually-aware swapping would take a lot more effort.
This looks like homework, so I'll limit my answer to a couple of hints.
I would accumulate the result in a StringBuilder (called sb in what follows).
I would have a loop (for i = 0; i < w.length(); i += 2). In this loop I would do two things:
if i + 1 is within the bounds of the string, I'd append the i + 1-th character to sb;
append the i-th character to sb.
At the end, call sb.toString().

Categories