Related
I have a string "Hello, World!" that I have to convert into a char array. I then found the index of the char ',' - to which I want to create a new char array that contains " World!, Hello".
I've got the first index of the char array moved to the back - such that it prints out "ello, World!H".
How can I use my variable indexDelimiter to move the rest of the char arrays (as well as the ',') to the back? I've been looking at this problem forever, and I'm very confused as to how I could go about this.
I can't use ListArray. I has to be an Array.
public class ArrayTest {
public static void main(String[] args) {
String s = "Hello, World!";
char[] oldCharArray = s.toCharArray();
char[] newCharArray = new char[oldCharArray.length];
char delimiter = ',';
int indexDelimiter = new String(oldCharArray).indexOf(delimiter);
for (int i = 0; i < oldCharArray.length - 1; i++) {
newCharArray[i] = oldCharArray[i + 1];
}
newCharArray[oldCharArray.length - 1] = oldCharArray[0];
for (int i = 0; i < newCharArray.length; i++) {
System.out.print(newCharArray[i]);
}
// This prints out "ello, World!H" but I want " World!, Hello"
}
}
This code will produce "World!,Hello", take a look and see if it meets your needs.
public static void main(String args[]) {
String s = "Hello, World!";
char[] oldCharArray = s.toCharArray();
char[] newCharArray = new char[oldCharArray.length];
char delimiter = ',';
int indexDelimiter = new String(oldCharArray).indexOf(delimiter);
int i = 0;
for (i = 0; i < oldCharArray.length-indexDelimiter-1; i++) {
newCharArray[i] = oldCharArray[indexDelimiter + i + 1];
}
newCharArray[i] = delimiter;
i++;
int j = i;
while (i < oldCharArray.length) {
newCharArray[i] = oldCharArray[i - j];
i++;
}
System.out.println(newCharArray);
}
If you mean backward, you can reverse the by splitting it first
public char[] reverse_comma_split(String str) {
String[] spl = str.split(",");
String reversed = new String();
for (int i = spl.length - 1; i >= 0; i--) {
reversed += spl[i];
if (i != 0)
reversed += ", ";
}
return reversed.toCharArray();
}
Calling reverse_comma_split("Hello, world!") would return a char array of " world!, Hello"
However, if you insist to get uppercase char in every split, you can modify the loop in which spl[i] to spl[i].substring(0, 1).toUpperCase() + spl[i].substring(1)
Am trying to reverse a string using a method in java, I can fetch all the elements of the string and print them out in order via a loop, my problem is reversing the string such that the first comes last and the last comes first, I tried to find a reverse function to no avail... Here is what I have so far...
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
int len = name1.length();
for (int i = 0; i <= len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
That loop succeeds in printing out the single characters from the string.
You can use StringBuilder like this:
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString {
public static void main(String[] args) {
String input = "Geeks for Geeks";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1 = input1.reverse();
// print reversed String
System.out.println(input1);
}
}
You can also modify your code to do this:
1 -
for (int i = 0; i <= len; ++i) {
char b = name1[len - i];
System.out.println(b + " ");
}
2 -
for (int i = len; i >= 0; --i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
Using Java 9 codePoints stream you can reverse a string as follows. This example shows the reversal of a string containing surrogate pairs. It works with regular characters as well.
String str = "πππππ π¨π π£ππ";
String reversed = str.codePoints()
// Stream<String>
.mapToObj(Character::toString)
// concatenate in reverse order
.reduce((a, b) -> b + a)
.get();
System.out.println(reversed); // πππ£π π¨ π ππππ
See also: Reverse string printing method
You simply need to loop through the array backwards:
for (int i = len - 1; i >= 0; i--) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
You start at the last element which has its index at the position length - 1 and iterate down to the first element (with index zero).
This concept is not specific to Java and also applies to other data structures that provide index based access (such as lists).
Use the built-in reverse() method of the StringBuilder class.
private static void palindrome() {
String name1;
StringBuilder input = new StringBuilder();
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
input.append(name1);
input.reverse();
System.out.println(input);
}
Added reverse() function for your understanding
import java.util.Scanner;
public class P3 {
public static void main(String[] args) {
palindrome();
}
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
String nameReversed = reverse(name1);
int len = name1.length();
for (int i = 0; i < len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
private static String reverse(String name1) {
char[] arr = name1.toCharArray();
int left = 0, right = arr.length - 1;
while (left < right) {
//swap characters first and last positions
char temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return new String(arr);
}
}
you can try the build-in function charAt()
private String reverseString2(String str) {
if (str == null) {
return null;
}
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
result = result + str.charAt(i);
}
return result;
}
public void test(){
System.out.println(reverseString2("abcd"));
}
see also rever a string in java
String reversed = new StringBuilder(originalString).reverse().toString();
I have "Hello World" kept in a String variable named hi.
I need to print it, but reversed.
How can I do this? I understand there is some kind of a function already built-in into Java that does that.
Related: Reverse each individual word of βHello Worldβ string with Java
You can use this:
new StringBuilder(hi).reverse().toString()
StringBuilder was added in Java 5. For versions prior to Java 5, the StringBuffer class can be used instead β it has the same API.
For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:
public static String reverse(String input){
char[] in = input.toCharArray();
int begin=0;
int end=in.length-1;
char temp;
while(end>begin){
temp = in[begin];
in[begin]=in[end];
in[end] = temp;
end--;
begin++;
}
return new String(in);
}
public static String reverseIt(String source) {
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--){
dest.append(source.charAt(i));
}
return dest.toString();
}
http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm
String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);
I am doing this by using the following two ways:
Reverse string by CHARACTERS:
public static void main(String[] args) {
// Using traditional approach
String result="";
for(int i=string.length()-1; i>=0; i--) {
result = result + string.charAt(i);
}
System.out.println(result);
// Using StringBuffer class
StringBuffer buffer = new StringBuffer(string);
System.out.println(buffer.reverse());
}
Reverse string by WORDS:
public static void reverseStringByWords(String string) {
StringBuilder stringBuilder = new StringBuilder();
String[] words = string.split(" ");
for (int j = words.length-1; j >= 0; j--) {
stringBuilder.append(words[j]).append(' ');
}
System.out.println("Reverse words: " + stringBuilder);
}
Take a look at the Java 6 API under StringBuffer
String s = "sample";
String result = new StringBuffer(s).reverse().toString();
Here is an example using recursion:
public void reverseString() {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String reverseAlphabet = reverse(alphabet, alphabet.length()-1);
}
String reverse(String stringToReverse, int index){
if(index == 0){
return stringToReverse.charAt(0) + "";
}
char letter = stringToReverse.charAt(index);
return letter + reverse(stringToReverse, index-1);
}
Here is a low level solution:
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inpStr = in.nextLine();
System.out.println("Original String :" + inpStr);
char temp;
char[] arr = inpStr.toCharArray();
int len = arr.length;
for(int i=0; i<(inpStr.length())/2; i++,len--){
temp = arr[i];
arr[i] = arr[len-1];
arr[len-1] = temp;
}
System.out.println("Reverse String :" + String.valueOf(arr));
}
}
I tried, just for fun, by using a Stack. Here my code:
public String reverseString(String s) {
Stack<Character> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.empty()) {
sb.append(stack.pop());
}
return sb.toString();
}
Since the below method (using XOR) to reverse a string is not listed, I am attaching this method to reverse a string.
The Algorithm is based on :
1.(A XOR B) XOR B = A
2.(A XOR B) XOR A = B
Code snippet:
public class ReverseUsingXOR {
public static void main(String[] args) {
String str = "prateek";
reverseUsingXOR(str.toCharArray());
}
/*Example:
* str= prateek;
* str[low]=p;
* str[high]=k;
* str[low]=p^k;
* str[high]=(p^k)^k =p;
* str[low]=(p^k)^p=k;
*
* */
public static void reverseUsingXOR(char[] str) {
int low = 0;
int high = str.length - 1;
while (low < high) {
str[low] = (char) (str[low] ^ str[high]);
str[high] = (char) (str[low] ^ str[high]);
str[low] = (char) (str[low] ^ str[high]);
low++;
high--;
}
//display reversed string
for (int i = 0; i < str.length; i++) {
System.out.print(str[i]);
}
}
}
Output:
keetarp
As others have pointed out the preferred way is to use:
new StringBuilder(hi).reverse().toString()
But if you want to implement this by yourself, I'm afraid that the rest of responses have flaws.
The reason is that String represents a list of Unicode points, encoded in a char[] array according to the variable-length encoding: UTF-16.
This means some code points use a single element of the array (one code unit) but others use two of them, so there might be pairs of characters that must be treated as a single unit (consecutive "high" and "low" surrogates).
public static String reverseString(String s) {
char[] chars = new char[s.length()];
boolean twoCharCodepoint = false;
for (int i = 0; i < s.length(); i++) {
chars[s.length() - 1 - i] = s.charAt(i);
if (twoCharCodepoint) {
swap(chars, s.length() - 1 - i, s.length() - i);
}
twoCharCodepoint = !Character.isBmpCodePoint(s.codePointAt(i));
}
return new String(chars);
}
private static void swap(char[] array, int i, int j) {
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:/temp/reverse-string.txt");
StringBuilder sb = new StringBuilder("Linear B Syllable B008 A: ");
sb.appendCodePoint(65536); //http://unicode-table.com/es/#10000
sb.append(".");
fos.write(sb.toString().getBytes("UTF-16"));
fos.write("\n".getBytes("UTF-16"));
fos.write(reverseString(sb.toString()).getBytes("UTF-16"));
}
Using charAt() method
String name = "gaurav";
String reversedString = "";
for(int i = name.length()-1; i>=0; i--){
reversedString = reversedString + name.charAt(i);
}
System.out.println(reversedString);
Using toCharArray() method
String name = "gaurav";
char [] stringCharArray = name.toCharArray();
String reversedString = "";
for(int i = stringCharArray.length-1; i>=0; i--) {
reversedString = reversedString + stringCharArray[i];
}
System.out.println(reversedString);
Using reverse() method of the Stringbuilder
String name = "gaurav";
String reversedString = new StringBuilder(name).reverse().toString();
System.out.println(reversedString);
Check https://coderolls.com/reverse-a-string-in-java/
It is very simple in minimum code of lines
public class ReverseString {
public static void main(String[] args) {
String s1 = "neelendra";
for(int i=s1.length()-1;i>=0;i--)
{
System.out.print(s1.charAt(i));
}
}
}
This did the trick for me
public static void main(String[] args) {
String text = "abcdefghijklmnopqrstuvwxyz";
for (int i = (text.length() - 1); i >= 0; i--) {
System.out.print(text.charAt(i));
}
}
1. Using Character Array:
public String reverseString(String inputString) {
char[] inputStringArray = inputString.toCharArray();
String reverseString = "";
for (int i = inputStringArray.length - 1; i >= 0; i--) {
reverseString += inputStringArray[i];
}
return reverseString;
}
2. Using StringBuilder:
public String reverseString(String inputString) {
StringBuilder stringBuilder = new StringBuilder(inputString);
stringBuilder = stringBuilder.reverse();
return stringBuilder.toString();
}
OR
return new StringBuilder(inputString).reverse().toString();
System.out.print("Please enter your name: ");
String name = keyboard.nextLine();
String reverse = new StringBuffer(name).reverse().toString();
String rev = reverse.toLowerCase();
System.out.println(rev);
I used this method to turn names backwards and into lower case.
One natural way to reverse a String is to use a StringTokenizer and a stack. Stack is a class that implements an easy-to-use last-in, first-out (LIFO) stack of objects.
String s = "Hello My name is Sufiyan";
Put it in the stack frontwards
Stack<String> myStack = new Stack<>();
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
myStack.push(st.nextToken());
}
Print the stack backwards
System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
while (!myStack.empty()) {
System.out.print(myStack.pop());
System.out.print(' ');
}
System.out.println('"');
public String reverse(String s) {
String reversedString = "";
for(int i=s.length(); i>0; i--) {
reversedString += s.charAt(i-1);
}
return reversedString;
}
public class Test {
public static void main(String args[]) {
StringBuffer buffer = new StringBuffer("Game Plan");
buffer.reverse();
System.out.println(buffer);
}
}
All above solution is too good but here I am making reverse string using recursive programming.
This is helpful for who is looking recursive way of doing reverse string.
public class ReversString {
public static void main(String args[]) {
char s[] = "Dhiral Pandya".toCharArray();
String r = new String(reverse(0, s));
System.out.println(r);
}
public static char[] reverse(int i, char source[]) {
if (source.length / 2 == i) {
return source;
}
char t = source[i];
source[i] = source[source.length - 1 - i];
source[source.length - 1 - i] = t;
i++;
return reverse(i, source);
}
}
You can also try this:
public class StringReverse {
public static void main(String[] args) {
String str = "Dogs hates cats";
StringBuffer sb = new StringBuffer(str);
System.out.println(sb.reverse());
}
}
Procedure :
We can use split() to split the string .Then use reverse loop and add the characters.
Code snippet:
class test
{
public static void main(String args[])
{
String str = "world";
String[] split= str.split("");
String revers = "";
for (int i = split.length-1; i>=0; i--)
{
revers += split[i];
}
System.out.printf("%s", revers);
}
}
//output : dlrow
It gets the value you typed and returns it reversed ;)
public static String reverse (String a){
char[] rarray = a.toCharArray();
String finalvalue = "";
for (int i = 0; i < rarray.length; i++)
{
finalvalue += rarray[rarray.length - 1 - i];
}
return finalvalue;
}
public String reverseWords(String s) {
String reversedWords = "";
if(s.length()<=0) {
return reversedWords;
}else if(s.length() == 1){
if(s == " "){
return "";
}
return s;
}
char arr[] = s.toCharArray();
int j = arr.length-1;
while(j >= 0 ){
if( arr[j] == ' '){
reversedWords+=arr[j];
}else{
String temp="";
while(j>=0 && arr[j] != ' '){
temp+=arr[j];
j--;
}
j++;
temp = reverseWord(temp);
reversedWords+=temp;
}
j--;
}
String[] chk = reversedWords.split(" ");
if(chk == null || chk.length == 0){
return "";
}
return reversedWords;
}
public String reverseWord(String s){
char[] arr = s.toCharArray();
for(int i=0,j=arr.length-1;i<=j;i++,j--){
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return String.valueOf(arr);
}
public static void main(String[] args) {
String str = "Prashant";
int len = str.length();
char[] c = new char[len];
for (int j = len - 1, i = 0; j >= 0; j--, i++) {
c[i] = str.charAt(j);
}
str = String.copyValueOf(c);
System.out.println(str);
}
public void reverString(){
System.out.println("Enter value");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
String str=br.readLine();
char[] charArray=str.toCharArray();
for(int i=charArray.length-1; i>=0; i--){
System.out.println(charArray[i]);
}
}
catch(IOException ex){
}
recursion:
public String stringReverse(String string) {
if (string == null || string.length() == 0) {
return string;
}
return stringReverse(string.substring(1)) + string.charAt(0);
}
Sequence of characters (or) StringString's Family:
String testString = "Yashwanth#777"; // ~1β1β4βD800ββΒ«2Β²β°
Using Java 8 Stream API
First we convert String into stream by using method CharSequence.chars(), then we use the method IntStream.range to generate a sequential stream of numbers. Then we map this sequence of stream into String.
public static String reverseString_Stream(String str) {
IntStream cahrStream = str.chars();
final int[] array = cahrStream.map( x -> x ).toArray();
int from = 0, upTo = array.length;
IntFunction<String> reverseMapper = (i) -> ( Character.toString((char) array[ (upTo - i) + (from - 1) ]) );
String reverseString = IntStream.range(from, upTo) // for (int i = from; i < upTo ; i++) { ... }
.mapToObj( reverseMapper ) // array[ lastElement ]
.collect(Collectors.joining()) // Joining stream of elements together into a String.
.toString(); // This object (which is already a string!) is itself returned.
System.out.println("Reverse Stream as String : "+ reverseString);
return reverseString;
}
Using a Traditional for Loop
If you want to reverse the string then we need to follow these steps.
Convert String into an Array of Characters.
Iterate over an array in reverse order, append each Character to temporary string variable until the last character.
public static String reverseString( String reverse ) {
if( reverse != null && reverse != "" && reverse.length() > 0 ) {
char[] arr = reverse.toCharArray();
String temp = "";
for( int i = arr.length-1; i >= 0; i-- ) {
temp += arr[i];
}
System.out.println("Reverse String : "+ temp);
}
return null;
}
Easy way to Use reverse method provided form StringBuffer or StringBuilder Classes
StringBuilder and StringBuffer are mutable sequence of characters. That means one can change the value of these object's.
StringBuffer buffer = new StringBuffer(str);
System.out.println("StringBuffer - reverse : "+ buffer.reverse() );
String builderString = (new StringBuilder(str)).reverse().toString;
System.out.println("StringBuilder generated reverse String : "+ builderString );
StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized so it is thread safe.
public static String revString(String str){
char[] revCharArr = str.toCharArray();
for (int i=0; i< str.length()/2; i++){
char f = revCharArr[i];
char l = revCharArr[str.length()-i-1];
revCharArr[i] = l;
revCharArr[str.length()-i-1] = f;
}
String revStr = new String(revCharArr);
return revStr;
}
Simple For loop in java
public void reverseString(char[] s) {
int length = s.length;
for (int i = 0; i < s.length / 2; i++) {
// swaping character
char temp = s[length - i - 1];
s[length - i - 1] = s[i];
s[i] = temp;
}
}
How to reverse String in place in Java
input String : 1234
Output Should : 4321
what i have tried.
public static void main(String args[])
{
String number = "1234";
System.out.println("original String: " + number); String reversed = inPlaceReverse(number);
System.out.println("reversed String: " + reversed);
}
public static String inPlaceReverse(final String input)
{
final StringBuilder builder = new StringBuilder(input);
int length = builder.length();
for (int i = 0; i < length / 2; i++)
{
final char current = builder.charAt(i);
final int otherEnd = length - i - 1;
builder.setCharAt(i, builder.charAt(otherEnd)); // swap
builder.setCharAt(otherEnd, current);
}
return builder.toString();
}
i am getting answer like:
reversed String: 4231 as i expected 4321.
If your teacher wants to see your work then you should manipulate the chars directly. Something like the following should be enough to let you spot the mistake:
public static String reverse(String orig)
{
char[] s = orig.toCharArray();
final int n = s.length;
final int halfLength = n / 2;
for (int i=0; i<halfLength; i++)
{
char temp = s[i];
s[i] = s[n-1-i];
s[n-1-i] = temp;
}
return new String(s);
}
It can be even simpler using StringBuilder's reverse() function:
public static String inPlaceReverse(String input) {
StringBuilder builder = new StringBuilder(input);
return builder.reverse().toString();
}
public static String inPlaceReverse(String number) {
char[] ch = number.toCharArray();
int i = 0;
int j = number.length()-1;
while (i < j) {
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
i++;
j--;
}
return String.valueOf(ch);
}
1. Using Character Array:
public String reverseSting(String inputString) {
char[] inputStringArray = inputString.toCharArray();
String reverseString = "";
for (int i = inputStringArray.length - 1; i >= 0; i--) {
reverseString += inputStringArray[i];
}
return reverseString;
}
2. Using StringBuilder:
public String reverseSting(String inputString) {
StringBuilder stringBuilder = new StringBuilder(inputString);
stringBuilder = stringBuilder.reverse();
return stringBuilder.toString();
}
OR
return new StringBuilder(inputString).reverse().toString();
This is an interview question.
Reverse a String in place :
public class Solution4 {
public static void main(String[] args) {
String a = "Protijayi";
System.out.println(reverse(a)); //iyajitorP
}
private static String reverse(String a) {
char[] ca = a.toCharArray();
int start = 0 ; int end = a.length()-1;
while(end > start) {
swap(ca,start,end);
start++;
end--;
}//while
return new String(ca);
}
private static void swap(char[] ca, int start, int end) {
char t = ca[start];
ca[start] = ca[end];
ca[end] = t ;
}
}
Mind also, that you can avoid using additional memory during the swap, though having some extra computation.
public class StringReverser {
public static String reverseStringInPlace(String toReverse) {
char[] chars = toReverse.toCharArray();
int inputStringLength = toReverse.length();
for (int i = 0; i < inputStringLength / 2; i++) {
int toMoveBack = toReverse.charAt(i);
int toMoveForward = toReverse.charAt(inputStringLength - i - 1);
//swap
toMoveForward = toMoveBack - toMoveForward;
toMoveBack -= toMoveForward;
toMoveForward += toMoveBack;
chars[i] = (char) toMoveBack;
chars[inputStringLength - i - 1] = (char) toMoveForward;
}
return String.valueOf(chars);
}
public static void main(String[] args) {
System.out.println(reverseStringInPlace("asd0")); // output: 0dsa
System.out.println(reverseStringInPlace("sd0")); // output: 0ds
System.out.println(reverseStringInPlace("")); // output: empty
System.out.println(reverseStringInPlace("-")); // output: -
System.out.println(reverseStringInPlace("ABD+C")); // output: C+DBA
System.out.println(reverseStringInPlace("ε")); // output: ε
System.out.println(reverseStringInPlace("εζ§γ")); // output: γζ§ε
System.out.println(reverseStringInPlace("MarΓtimo")); // output: omitΓraM
}
}
Relevant to swap discussion can be found here:
How to swap two numbers without using temp variables or arithmetic operations?
Convert the string to a character array first and then use recursion.
public void reverseString(char[] s) {
helper(0, s.length - 1, s);
}
private void helper(int left, int right, char[] s){
if(left >= right) {
return;
}
char temp = s[left];
s[left++] = s[right];
s[right--] = temp;
helper(left, right, s);
}
So with the input [1,2,3,4], the helper function will be called as follows :
1. helper(0, 3, [1,2,3,4]), Swap 1 and 4
2. helper(1, 2, [1,2,3,4]), Swap 2 and 3
3. helper(2, 1, [1,2,3,4]) Terminates, left is now greater than right
After converting into char array. Just swap the both ends ( first index, last index) and move towards each other(first index to last index and from last index to first) until the crossing.
public void reverseString(char[] s) {
int start = 0;
int end = s.length-1;
char temp = ' ';
while((start)<(end)){
temp = s[start];
s[start] = s[end];
s[end] = temp;
start++;
end--;
}
System.out.println(s);
}
I want to store the value of 2 strings str1, str2 respectively into 3rd string strContainer (without using library method).
My Algorithm is:
1. convert str1 and str2 into character array charArray1 and charArray2 respectively.
2. Count the sum of the length of both character array in counter variable (sum of the length charArray and charArray2)
3. Sum of the both char Arrays (as counter) is equivalent to a new char Array charContainer.
4. Iterate a loop as below
charContainer[ith index] += charArray1[ith index];
and
charContainer[ith index] += charArray2[ith index];
5. Convert charContainer into string and display as strContainer.
My code so far:
public class StringConcat{
int counter; // counting the length of char arrays
String str1 = "FirstString";
String str2 = "SecondString";
//for counting the length of both char arrays
public int countingLength(String str){
char[] strToCharArray = str.toCharArray();
for(char temp : strToCharArray){
counter++;
}
}
//converting string into char array
char[] charArray1 = str1.tocharArray();
char[] charArray2 = str1.tocharArray();
//stores both char array
char[] charContainer=new char[counter];//how to take counter as an index value here
//for storing charArray1 into charContainer
for(int i=0; i<charContainer.length; i++) {
if(charArray1 != null){
charContainer[i] += charArray1[i];
} else
return charArray2;
}
//for storing charArray2 into charContainer
for(int i=0; i<charContainer.length; i++) {
if(charArray2 != null){
charContainer[i] += charArray1[i];
} else
return charArray1;
}
//converting charContainer char array into string strContainer.
String strContainer = new String(charContainer);
//alternative : String strContainer = String.valueOf(charContainer);
public static void main(String args[]){
/*Here i can call (As i'm not sure)
StringConcat obj1 = new StringConcat();
obj1.countingLength(str1);
StringConcat obj2 = new StringConcat();
obj2.countingLength(str2);
*/
System.out.println("String Container : " +strContainer);
}
}//end of the class
Issues:
How to call countingLength() method for both strings str1 and str2 ?
How to assign as an index value of charContainer as counter (sum of the both char arrays) ?
How to call StringLengthCounter() method? I can't see any method with that name.. I'm sorry but that is not the problem here, the problem is that this is not even valid code.
I don't mean to be harsh but there are sintax error all around and the program logic is wrong in many ways.
Please take a look at the following code and try to figure out how it works, I think it does what you want.
If something isn't clear just ask.
public class StringConcat{
public static String strcat(String str1, String str2){
//converting string into char array
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
int counter=charArray1.length+charArray2.length;
//stores both char array
char[] charContainer=new char[counter];
//for storing charArray1 into charContainer
int i=0;
for(; i<charArray1.length; i++) {
charContainer[i]=charArray1[i];
}
//for storing charArray2 into charContainer
for(int j=0; i<counter; j++,i++) {
charContainer[i]=charArray2[j];
}
//converting charContainer char array into string
return new String(charContainer);
}
public static void main(String args[]){
String str1 = "FirstString";
String str2 = "SecondString";
String strContainer = strcat(str1,str2);
System.out.println("String Container : " +strContainer);
}
}//end of the class
import java.io.*;
class Concatenation
{
public static void main(String []args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i=0;
String s1,s2;
System.out.print("Enter the first string:");
s1=br.readLine();
System.out.print("Enter the Second string:");
s2=br.readLine();
char s3[]=new char[s1.length()+s2.length()];
for(;i<s1.length();i++)
s3[i]=s1.charAt(i);
for(int j=0;j<s2.length();j++)
s3[i++]=s2.charAt(j);
System.out.println("Result:"+new String(s3));
}
}
public class Conc {
String s1="java",s2="programming",s3="";
int l=s1.length(),m=s2.length(),i,j;
public String conca(String s1,String s2){
for(i=0;i<=l-1;i++){
s3+=s1.charAt(i);
}
for(j=0;j<=m-1;j++){
s3+=s2.charAt(j);
}
System.out.println(s3);
return s3;
}
public static void main(String[] args) {
Conc obj1=new Conc();
obj1.conca("java","programming");
}
}
public class StringConcatination {
public static String concate(String s1,String s2){
String s3="";
for(int i=0;i<s1.length();i++){
s3+=s1.charAt(i);
}
for(int j=0;j<s2.length();j++){
s3+=s2.charAt(j);
}
return s3;
}
public static void main(String[] args) {
System.out.println(concate("java","programming"));
}
}
public static void concat(String a, String b) {
/**
* String result = a + b;
*/
/**
* Logic goes here.
*
* Need to iterate through chars
*
* Need to get total length
*/
int totalLength = a.length();
totalLength += b.length();
char[] result = new char[totalLength];
char[] arrayFromA = a.toCharArray();
char[] arrayFromB = b.toCharArray();
int count = 0;
System.out.println("Total Length of String: "+ totalLength);
for (int i = 0; i < arrayFromA.length; i++) {
result[i] = arrayFromA[i];
count++;
}
for (int j = 0; j < arrayFromB.length; j++) {
result[count] = arrayFromB[j];
count++;
}
System.out.println(new String(result));
}