How to concatenate a character to every element of an Array (Java) - java

I am purely novice in Java. Yesterday I was working on a home work. I had to split a string character by character and store those letters in an array. Then print this array. (DONE)
Then concatenate a single character (let's say 'a') with the every element of that array and print the results. (NOT DONE)
And at-last concatenate all those elements and create a string and print it. (NOT DONE)
String name = "Rocky";
int i;
int size = name.length();
char strings[] = new char[size];
for (i = 0; i <= size; i++) {
strings[i] = name.charAt(i);
System.out.println(strings[i]); // 1st output is done
}
The second output (concatenated char) should be:
Ra
oa
ca
ka
ya
The third output (single concatenated string) should be:
Raoacakaya
Finally I have done this and it works after-all its my homework maybe its not all up to standard. Thanks all for for replying.
String a="a";
String name="Rocky";
String temp="";
int i;
String array[]=name.split("");
String array2[]=new String[name.length()+1];
for(i=1; i<=name.length();i++)
{
System.arraycopy( array, 0, array2, 0, array.length );
System.out.println(array[i]);
}
System.out.println();
for(i=1; i<=name.length();i++)
{
System.out.println(array2[i]+a);
array2[i]=array2[i]+a;
}
for (i=1; i<array2.length;i++)
{
temp=temp+array2[i];
}
System.out.println();
System.out.println(temp);
}
}

First, you don't need to use int size, just use name.length() instead. As for the outputs, you can do it this way:
char c2 = 'a';
String all = "";
for(char c : strings)
{
String s = String.valueOf(c) + String.valueOf(c2);
System.out.println(s); // 2nd output
all += s;
}
System.out.println(all); // 3rd output

I hope I get you right. If so, this should do the trick:
public static void homeWork() {
final String name = "Rocky";
final char toAdd = 'a';
char[] array = name.toCharArray();
String concatenated = concatenate(array, toAdd);
System.out.println("Concatenated : " + concatenated);
}
public static String concatenate(char[] array, char toAdd) {
StringBuilder buidler = new StringBuilder();
for (char c : array) {
String toAppend = String.valueOf(c) + String.valueOf(toAdd);
System.out.println(toAppend);
buidler.append(toAppend);
}
return buidler.toString();
}
You run through the array with a for each loop and append
all characters with the letter you put in "toAdd".
Print the result for every loop and print the end result,
after the method returns.
Output:
Ra
oa
ca
ka
ya
Concatenated : Raoacakaya

For 2nd output:
char a = 'a';
String all = "";
for(char c : strings)
{
String s = String.valueOf(c) + String.valueOf(a);
System.out.println(s);
}
For 3rd output:
char a = 'a';
String wholeString= "";
for(char c : strings)
{
String s = String.valueOf(c) + String.valueOf(a);
System.out.print(s);
wholeString+= s;
}
System.out.println(wholeString);

Related

if the characters are same then consider it only once in java language

So, i am basically new to java ,and there was this question on our programming test
input:ww:ii:pp:rr:oo
if the alphabets are same then consider only once
output:wipro
so i was able to remove the : from the input and was also able to separate them
my current output :[w,w,i,i,p,p,r,r,o,o]
but i am unable to consider the same characters only once,its been nearly 35 min :_(
String txt="ww:ii:pp::rr:oo";
String[] result= txt.split(":");
System.out.println(Arrays.toString(result));//1
String n11="";
for(String str:result){
n11 += str;
}
System.out.println(n11);//2
result=n11.split("");
System.out.println(Arrays.toString(result));//3
String n12="";
int i=0;
for(String i:result){
if(i.equals(i+1)){
continue;
}
else {
n12=n12+i;
}
}
System.out.println(n12);//4
}
output
[ww, ii, pp, , rr, oo]
wwiipprroo
[w, w, i, i, p, p, r, r, o, o]
[nullw, nullw, nulli, nulli, nullp, nullp, nullr, nullr, nullo, nullo]
Example:
public class GFG
{
/* Method to remove duplicates in a sorted array */
static String removeDupsSorted(String str)
{
int res_ind = 1, ip_ind = 1;
// Character array for removal of duplicate characters
char arr[] = str.toCharArray();
/* In place removal of duplicate characters*/
while (ip_ind != arr.length)
{
if(arr[ip_ind] != arr[ip_ind-1])
{
arr[res_ind] = arr[ip_ind];
res_ind++;
}
ip_ind++;
}
str = new String(arr);
return str.substring(0,res_ind);
}
/* Method removes duplicate characters from the string
This function work in-place and fills null characters
in the extra space left */
static String removeDups(String str)
{
// Sort the character array
char temp[] = str.toCharArray();
//Arrays.sort(temp);
str = new String(temp);
// Remove duplicates from sorted
return removeDupsSorted(str);
}
// Driver Method
public static void main(String[] args)
{
String str = "ww:ii:pp:rr:oo";
String str1 = str.replaceAll(":","");
System.out.println(removeDups(str1));
}
}
The source is taken from www.geeksforgeeks.org And added String str1 = str.replaceAll(":","");
Output:
Your first step is right. But, you have an error in i.equals(i+1) since i + 1 isn't is the next element. You should iterate the array like this:
for (int i = 0; i < result.length - 1; i ++) {
if (result[i].equals(result[i + 1])) {
// do the remove operation.
}
}

Doubling one letter with each new occurence

so I have task to double number of letter "a" every time it occurs in a string.
For example sentence "a cat walked on the road" , at the end must be "aa caaaat waaaaaaaalked on the roaaaaaaaaaaaaaaaa" . I had something like this on my mind but it doubles every charachter, not only "a".
public static void main(String[] args) {
String s = "a bear walked on the road";
String result = "";
int i = 0;
while(i<s.length()){
char a = s.charAt(i);
result = result + a + a;
i++;
}
System.out.println(result);
}
You need to check what the char a is (in your case, 'a'). Additionally, you do not repeat the characters more than twice in your code, hence not getting the answer you expected: result = result + a + a only adds 'a' twice, not giving you: "aa caaaat waaaaaaaalked...".
Here is the solution:
public static void main(String[] args) {
String s = "a bear walked on the road";
String result = "";
char lookingFor = 'a'; // Can change this to whatever is needed
int counter = 2;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == lookingFor) { // The current character is what we need to be repeated.
// Repeat the character as many times as counter is (each loop: 2, 4, 6, 8, ...)
for (int j = 0; j < counter; j++) {
result += lookingFor;
}
counter *= 2; // Double counter at every instance of 'a'
}
else { // The current char is not what we are looking for, so we just add it to our result.
result += s.charAt(i);
}
}
System.out.println(result);
}
The problems are:
you are doubling every character because you are not testing if it is an 'a' or not.
and you are not doubling the substitution each time.
Here is a modified version of your solution.
String s = "a bear walked on the road";
String result = "";
String sub = "aa";
int i = 0;
while(i<s.length()){
// get the character
char ch = s.charAt(i++);
//if it an a, append sub to result
// and double sub.
if (ch == 'a') {
result += sub;
sub += sub;
} else {
// otherwise, just append the character
result += ch;
}
}
Here is another way.
check each character and double the replacement each time an a is encountered.
String str = "a cat walked on the road";
StringBuilder sb = new StringBuilder();
String sub = "a";
for (String s : str.split("")) {
sb.append(s.equals("a") ? (sub += sub) : s);
}
System.out.println(sb);
prints
aa caaaat waaaaaaaalked on the roaaaaaaaaaaaaaaaad
Try this out:
public static void main(String[] args) {
char letterToSearch = 'a'
String myString = "a bear walked on the road";
StringBuilder result = new StringBuilder();
int occurrance = 0;
for (int i = 0; i < myString.length(); i++){
char currChar = myString.charAt(i);
if (currChar == letterToSearch){
occurrance+=1;
for (int j = 0; j < 2*occurrance; j++){
result.append(currChar);
}
} else {
result.append(currChar);
}
}
System.out.println(result);
}
The variable occurrance keeps track of how many as you have.

Java: Formatting issue. Grabbing unique characters from an array of strings and returning them

I'm having a problem getting the unique letters and digits out of an array of strings, and then returning them. I am having a formatting issue.
The given input is: ([abc, 123, efg]) and is supposed to return abcefg123,
however, mine returns: abc123efg
how can I fix this since arrays.sort() will end up putting the numbers first and not last?
Here is my method so far:
public static String getUniqueCharsAndDigits(String[] arr) {
String str = String.join(",", arr);
String myString = "";
myString = str.replaceAll("[^a-zA-Z0-9]", "");
for(int i = 0; i < str.length(); i++) {
if(Character.isLetterOrDigit((i))){
if(myString.indexOf(str.charAt(i)) == -1) {
myString = myString + str.charAt(i);
}
}
}
return myString;
}
What you want to do is create two strings, one with the letters, one with the digits.
public static String getUniqueCharsAndDigits(String[] arr) {
String str = String.join("", arr);
String myLetters, myDigits;
myLetters = myDigits = "";
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(Character.isLetter(c)){
if(myLetters.indexOf(c) == -1) {
myLetters += c;
}
} else if(Character.isDigit(c)){
if(myDigits.indexOf(c) == -1) {
myDigits += c;
}
}
}
//if they need to be sorted, sort each one individually here
return myLetters + myDigits;
}
I've modified your code and deleted the unnecessary parts of it.

Converting \n to String without \\n

How can I convert "\n" into a char[]? I want to do this because I want to do some string manipulation when \n is entered in the method as input. I know that if \\n is entered then the output will be \n as a string. I want to implement a method to take in input as \n not \\n to get the string result.
tests:
char[] arr = new char[2];
String str = "\n";
arr = str.toCharArray();
System.out.println(arr.length);
for (char c : arr) {
System.out.println(c);
}
ouput:
1
// newline empty space
my reverse string method
public static String reverseStr(String str) {
if ( str == null ) {
return null;
}
int len = str.length();
if (len <= 0) {
return "";
}
char[] strArr = new char[len];
int count = 0;
for (int i = len - 1; i >= 0; i--) {
strArr[count] = str.charAt(i);
count++;
}
return new String(strArr);
}
newlines are represented as 10 in ascii. you can try this.
char[] arr = new char[3];
int str = 10;
arr[0] = 'a';
arr[1] = (char)str;
arr[2] = 'c';
System.out.println(arr.length);
for (char c : arr) {
System.out.println(c);
}
One way to do it is by using Stringbuilder
String builder(StringBuilder has overloaded methods for char and Sting).
StringBuilder str= new StringBuilder();
str.append('\n'); or
str.append("\n");

Shifting characters within a string

String newStr;
public RandomCuriosity(String input){
newStr = input;
}
public void shiftChars(){
char[] oldChar = newStr.toCharArray();
char[] newChar = new char[oldChar.length];
newChar[0] = oldChar[oldChar.length-1];
for(int i = 1; i < oldChar.length; i++){
newChar[i] = oldChar[i-1];
}
newStr = String.valueOf(newChar);
}
I created a method that shifts characters forward by one. For example, the input could be:
The input: Stackoverflow
The output: wStackoverflo
How I did it is I mutated an instance of a string. Convert that string to a char array (calling it oldChar), assigned the last index of of oldChar as the first index of newChar, and made a for-loop that took the first index of oldChar as the second index of my new Char array and so forth. Lastly, I converted the char array back to a string.
I feel like I did way too much to do something very simple. Is there a more efficient way to do something like this?
EDIT Thanks for the great answers!
newStr = newStr.charAt(newStr.length() - 1) + newStr.substring(0, newStr.length() - 1);
You can made your life simpler :
public static void main (String[] args) throws java.lang.Exception {
String input = "Stackoverflow";
for(int i = 0; i < s.length(); i++){
input = shift(input);
System.out.println(input);
}
}
public static String shift(String s) {
return s.charAt(s.length()-1)+s.substring(0, s.length()-1);
}
Output :
wStackoverflo
owStackoverfl
lowStackoverf
flowStackover
rflowStackove
erflowStackov
verflowStacko
overflowStack
koverflowStac
ckoverflowSta
ackoverflowSt
tackoverflowS
Stackoverflow
You could use System.arrayCopy:
char[] oldChar = newStr.toCharArray();
char[] newChar = new char[oldChar.length];
newChar[0] = oldChar[oldChar.length - 1];
System.arrayCopy(oldChar, 0, newChar, 1, oldChar.length - 1);
You can use StringBuilders.
StringBuilder strb = new StringBuilder();
strb.append(oldChar[oldChar.length-1]).append(oldchar.substring(0, oldChar.length-1));
newStr = strb.toString();
try this..
String old = "String";
char first = old.charAt(old.length()-1);
String newString = first+old.substring(0,old.length()-1);
System.out.println(newString);
Another solution, but without using loops, for left and right shift:
public static String cyclicLeftShift(String s, int n){ //'n' is the number of characters to shift left
n = n%s.length();
return s.substring(n) + s.substring(0, n);
}
public static String cyclicRightShift(String s, int n){ //'n' is the number of characters to shift right
n = n%s.length();
return s.substring(s.length() - n , s.length()) + s.substring(0, s.length() - n);
}
By Java, u can shift it to forward by O(n) where n is how many times to go forward by character which space o(1)
public static String shiftChars(String s , int times) {
String temp = s;
for (int i = 0; i < times ; i++) {
temp = temp.charAt(temp.length()-1)+temp.substring(0, temp.length()-1);
}
return temp;
}

Categories

Resources