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");
Related
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 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,
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);
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
I had a string for eg "java education" which I have converted into bits. Now I have an array of bits. I want to convert it back into text. How to do this?
String s="Java Education";
char[] ch=s.toCharArray();
String g=" ";
StringBuilder sb= new StringBuilder();
for(char c:ch)
{
g=Integer.toBinaryString((int)c);
sb.append(ch);
}
char[] ch2= sb.toString.toCharArray();
I want to get back the text from the array ch2.
Try this
import java.util.Arrays;
public class DecodeBits {
public static void main(String[] args) {
String s = "Java Education";
char[] ch = s.toCharArray();
StringBuilder sb = new StringBuilder();
for (char c : ch) {
// Wen need a fix length
String g = String.format("%16s", Integer.toBinaryString((int) c)).replace(' ', '0');
// this seems to be typo
// sb.append(ch);
sb.append(g);
}
char[] ch2 = sb.toString().toCharArray();
int start = 0;
while (start < ch2.length - 15) {
char[] bits = Arrays.copyOfRange(ch2, start, start + 16);
int cValue = Integer.parseInt(new String(bits), 2);
char[] chars = Character.toChars(cValue);
System.out.print(chars[0]);
start += 16;
}
System.out.println("");
}
}
Here is my implementation:
String s="Java Education";
char[] ch=s.toCharArray();
String g="";
StringBuilder sb= new StringBuilder();
for(char c:ch)
{
g=Integer.toBinaryString((int)c);
if(g.length()<8){
for(int h=0; h<8-g.length(); h++){
g="0"+g;
}
}
sb.append(g);
sb.append(',');
}
char[] ch2= sb.toString().toCharArray();
String[] s3 = new String(ch2).split(",");
for(String t: s3){
String d="";
for(int x=t.length()-1; x>=0; x--) d+=t.charAt(x);
t=d;
int num=0;
for(int j=0; j<t.length(); j++){
num+=Integer.parseInt(""+t.charAt(j))*Math.pow(2, j);
}
System.out.print((char)num);
}