In Java,how can the letters in strings be doubled? - java

I'm a beginner no matter how you look at it, so bear with me here. The project is about having a string in the code and then doubling every letter in it, while tripling the exclamation points. Nothing else is doubled. It's supposed to take something like this:
The quick brown fox jumps over the lazy dog 3 times!
...and turn it into this:
Tthhee qquuiicckk bbrroowwnn ffooxx jjuummppss oovveerr tthhee llaazzyy ddoogg 3 ttiimmeess!!!
This is the code I tried, though it prints in numbers and takes a bunch of loops to complete instead of one:
String s = "The quick brown fox jumps over the lazy dog 3 times!";
String output = "";
int i = 0;
while (i < s.length()) {
char c = s.charAt(i);
if (s.charAt(i) == '!') {
output += c + c + c;
i++;
}
if (Character.isLetter(c) == true) {
output += c + c;
i++;
} else {
i++;
}
System.out.println(output);
}

You really should use a StringBuilder, but char + char produces a char not a String (it does numeric addition). You probably want output += "" + c + c + c; since it will convert the chars to a String and then append them. (Likewise for the line output += c + c;)

A clean solution could look like this:
String s = "The quick brown fox jumps over the lazy dog 3 times!";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '!') {
sb.append(c).append(c).append(c);
} else if (Character.isLetter(c)) {
sb.append(c).append(c);
} else {
sb.append(c);
}
}
String output = sb.toString();
System.out.println(output);
The problems it fixes
Your code will skip a character after it encounters a '!'. You go into the first if, increment i correct, but then return to the rest of the code below, hit the next if, condition is false because ! is not a letter, so it goes in to else path and increments i a second time. You should ether use continue to prevent fall-through or use if .. else if .. else which enforces mutually exclusive flow as well.
A while loop is IMO more complicated to read than a for loop. You also don't have to increment i like 3 times. Once at the end of the while loop would be enough.
String concatenation in loops is best done with a StringBuilder. It can also append char without converting it to a number.
You forgot that you have to append c once when it's no special case.
You don't want to do System.out.println(output); inside the loop but afterwards. That's why you saw a lot more output lines than expected
formatting hiding issues like the one above

String s = "The quick brown fox jumps over the lazy dog 3 times!";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char temp = s.charAt(i);
builder.append(temp);
if (Character.isLetter(temp)) {
builder.append(temp);
} else if (temp == '!') {
builder.append(temp).append(temp);
}
}
System.out.println("Result: " + builder.toString());

You should convert the numbers back in characters first through a so called cast
like (char) output.
Try it and play around with it, learning and experimenting is the best thing about a beginning ;-)
Hope it helps.

Using a StringBuilder gives a short and clear solution :
String s = "The quick brown fox jumps over the lazy dog 3 times!";
StringBuilder sb = new StringBuilder();
for (int i=0 ; i<s.length() ; i++) {
String ch = s.charAt(i) + "";
sb.append(ch.matches("\\s") ? ch : ch + ch);
}
System.out.println(sb.toString());

Character is a number that represents the actual english character. Adding two characters will give you just a new number that number will represent some new character .
Use StringBuilder class for what you are doing.

This code worked fine for me...
String s = "The quick brown fox jumps over the lazy dog 3 times!";
String output = "";
int n = s.length();
for(int i = 0; i<n; i++){
String sub = s.substring(i, i+1);
output = output + sub + sub;
}
System.out.println(output);

Instead of printing the string what I think you are doing is printing the numbers asoociated with each character added together.
Add a "" into your concatenation, i.e. output+= "" + c + c;
But make sure to add the empty string before you add the characters otherwise it will add the characters together, giving you a number, and then converting it to a string.
Also, in your else statement you might want to add an output+= c line, otherwise it looks like you will lose your number 3 and your spaces.

Related

StringBuilder deleteCharAt() function " String index out of range : 6 "

Code and Error
Error 2
hey Guys see the Image and help me out to sort out this issue
It is the first code and it runs perfectly but when i use the same approach in the blow code it have some error
" For error detail open image link "
String str = "Samaarth";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(3);
System.out.println(sb.toString());
This is where the error start and the error is because of DeleteCharAt() function but in the above code this function works perfectly but here it is not
IDK why so please help me out to sort our this issue
String str= "aaabccddd";
StringBuilder sb = new StringBuilder(str);
for (int i = 0; i < str.length() -1; i++) {
if (sb.charAt(i) == sb.charAt(i + 1)) {
sb.deleteCharAt(i);
//sb.deleteCharAt(i+1);
}
}
System.out.println(sb.toString());
Samarath, you both modify the string and advance the counter.
This is wrong. Consider the string "aaaa"
This is what your code does:
i = 0: you find the duplicate, remove it. The string becomes "aaa".
Then you advance the position: i becomes 1
i = 1: the string is "a|aa" (the vertical bar shows the position).
You find the duplicate at position 1. You kill it, the string
becomes "aa", but you advance the position one again: i becomes 2
At this step the for loop ends and your string is "aa".
Instead the algorithm should use while loop: "while there are duplicates, kill them!"
String str= "aaabccddd";
StringBuilder sb = new StringBuilder(str);
int i = 0;
while (i < sb.length()-1) {
if (sb.charAt(i) == sb.charAt(i + 1)) {
sb.deleteCharAt(i);
// Do not increment -- kill all duplicates
} else {
// Either not a duplicate, or all duplicated killed
// Advance one char
i++;
}
}
System.out.println(sb.toString());
The output is abcd.
If you are inclined to use for loop, then iterate in the reverse order:
String str= "aaabccddd";
StringBuilder sb = new StringBuilder(str);
for (int i = sb.length()-1; i > 0; i--) {
if (sb.charAt(i) == sb.charAt(i - 1)) {
// Note charAt(i - 1) - we compare with the preceding character
sb.deleteCharAt(i);
// The string squeezes by one char, but the decremented position
// will follow
}
}
System.out.println(sb.toString());
The output is abcd
The problem is you are using for loop and you are actually changing/mutating StringBuilder instance at the same time, so the .length() will not be fixed and eventually you will try to reach non-existing index in your for loop and exception will be thrown.
EDIT:
Add these two lines inside your for loop if statement, just before you invoke deleteCharAt() method:
System.out.println("Value of i is: " + i);
System.out.println("StringBuilder length is: " + sb.length());
"i" represents index you are trying to delete, and sb.length() will display actual length of the StringBuilder.

How do you add a newline character in a string at specific indices?

I have a string:
String testString= "For the time being, programming is a consumer job, assembly line coding is the norm, and what little exciting stuff is being performed is not going to make it compared to the mass-marketed cräp sold by those who think they can surf on the previous half-century's worth of inventions forever"
like this: For the time being, programmi \n........\n.......\n
After each length of 20 characters in this string, I want to put a newline character \n for display in a TextView in Android.
You must have to use regex for achieve your task its fast and efficient. Try below code:-
String str = "....";
String parsedStr = str.replaceAll("(.{20})", "$1\n");
The (.{20}) will capture a group of 20 characters. The $1 in the second will put the content of the group. The \n will be then appended to the 20 characters which have been just matched.
How about something like that?
String s = "...whateverstring...";
for(int i = 0; i < s.length(); i += 20) {
s = new StringBuffer(s).insert(i, "\n").toString();
}
I know there is a technically better solution to use a StringBuffer and the insert method for that class, or even regex, but I'll show you a different algorithmic approach using String#substring:
String s = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
int offset = 0; // each time you add a new character, string has "shifted"
for (int i = 20; i + offset < s.length(); i += 20) {
// take first part of string, add a new line, and then add second part
s = s.substring(0, i + offset) + "\n" + s.substring(i + offset);
offset++;
}
System.out.println(s);
The result is this:
12345678901234567890
12345678901234567890
12345678901234567890
12345678901234567890
12345678901234567890
1234567890123456789
StringBuilder sb = new StringBuilder();
int done = 0;
while( done < s.length() ){
int todo = done + 20 < s.length() ? 20 : s.length() - done;
sb.append( s.substring( done, done + todo ) ).append( '\n' );
done += todo;
}
String result = sb.toString();
This also appends a newline at the end, but you can modify it easily to avoid that.

Java Stringbuilder.replace

Consider the following inputs:
String[] input = {"a9", "aa9", "a9a9", "99a99a"};
What would be the most efficient way whilst using a StringBuilder to replace any digit directly prior to a nine with the next letter after it in the alphabet?
After processing these inputs the output should be:
String[] output = {"b9", "ab9", "b9b9", "99b99a"}
I've been scratching my head for a while and the StringBuilder.setCharAt was the best method I could think of.
Any advice or suggestions would be appreciated.
Since you have to look at every character, you'll never perform better than linear in the size of the buffer. So you can just do something like
for (int i=1; buffer.length() ++i) // Note this starts at "1"
if (buffer.charAt[i] == '9')
buffer.setCharAt(i-1, buffer.getCharAt(i-1) + 1);
You can following code:
String[] input = {"a9", "aa9", "a9a9", "99a99a", "z9", "aZ9"};
String[] output = new String[input.length];
Pattern pt = Pattern.compile("([a-z])(?=9)", Pattern.CASE_INSENSITIVE);
for (int i=0; i<input.length; i++) {
Matcher mt = pt.matcher(input[i]);
StringBuffer sb = new StringBuffer();
while (mt.find()) {
char ch = mt.group(1).charAt(0);
if (ch == 'z') ch = 'a';
else if (ch == 'Z') ch = 'A';
else ch++;
mt.appendReplacement(sb, String.valueOf(ch));
}
mt.appendTail(sb);
output[i] = sb.toString();
}
System.out.println(Arrays.toString(output));
OUTPUT:
[b9, ab9, b9b9, 99b99a, a9, aA9]
You want to use a very simple state machine. For each character you're looping through in the input string, keep track of a boolean. If the character is a 9, set the boolean to true. If the character is a letter add one to the letter and set the boolean to false. Then add the character to the output stringbuilder.
For input you use a Reader. For output use a StringBuilder.
Use a 1 token look ahead parser technique. Here is some psuedoish code:
for (int index = 0; index < buffer.length(); ++index)
{
if (index < buffer.length() - 1)
{
if (buffer.charAt(index + 1) == '9')
{
char current = buffer.charAt(index) + 1; // this is probably not the best technique for this.
buffer.setCharAt(index, current);
}
}
}
another solution is for example to use
StringUtils.indexOf(String str, char searchChar, int startPos)
in a way as Ernest Friedman-Hill pointed, take this as experimental example, not the most performant

Java - Grouping repeated chars in a String

(This is not homework)
We have some extra exercices we can do, and i have done some.
But i got stuck in this one...
I need to make a program that given the string "loool" prints "l:1:o:3:l:1".
I have tried a bunch of combinations but i keep getting the same problem:
- I cant make the last repeated letter to get print ( Because with my code the next char needs to be different for a print to occurr).
String str = "loool";
StringBuilder sb = new StringBuilder();
int count = 1;
char before;
before = str.charAt(0);
for (int i = 1;i < str.length();i++) {
if (str.charAt(i) == before) {
count++;
}
else {
sb.append(before + ":" + count);
before = str.charAt(i);
count = 1;
}
}
return sb.toString();
You need to add some logic after your loop has finished, in order to deal with this problem. This logic will probably be very similar to the some of the code that you're using in the else block.

Add spaces between the characters of a string in Java?

I just want to add a space between each character of a string. Can anyone help me figuring out how to do this?
E.g. given "JAYARAM", I need "J A Y A R A M" as the result.
Unless you want to loop through the string and do it "manually" you could solve it like this:
yourString.replace("", " ").trim()
This replaces all "empty substrings" with a space, and then trims off the leading / trailing spaces.
ideone.com demonstration
An alternative solution using regular expressions:
yourString.replaceAll(".(?=.)", "$0 ")
Basically it says "Replace all characters (except the last one) with with the character itself followed by a space".
ideone.com demonstration
Documentation of...
String.replaceAll (including the $0 syntax)
The positive look ahead (i.e., the (?=.) syntax)
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
if (i > 0) {
result.append(" ");
}
result.append(input.charAt(i));
}
System.out.println(result.toString());
Iterate over the characters of the String and while storing in a new array/string you can append one space before appending each character.
Something like this :
StringBuilder result = new StringBuilder();
for(int i = 0 ; i < str.length(); i++)
{
result = result.append(str.charAt(i));
if(i == str.length()-1)
break;
result = result.append(' ');
}
return (result.toString());
Blow up your String into array of chars, loop over the char array and create a new string by succeeding a char by a space.
Create a StringBuilder with the string and use one of its insert overloaded method:
StringBuilder sb = new StringBuilder("JAYARAM");
for (int i=1; i<sb.length(); i+=2)
sb.insert(i, ' ');
System.out.println(sb.toString());
The above prints:
J A Y A R A M
This would work for inserting any character any particular position in your String.
public static String insertCharacterForEveryNDistance(int distance, String original, char c){
StringBuilder sb = new StringBuilder();
char[] charArrayOfOriginal = original.toCharArray();
for(int ch = 0 ; ch < charArrayOfOriginal.length ; ch++){
if(ch % distance == 0)
sb.append(c).append(charArrayOfOriginal[ch]);
else
sb.append(charArrayOfOriginal[ch]);
}
return sb.toString();
}
Then call it like this
String result = InsertSpaces.insertCharacterForEveryNDistance(1, "5434567845678965", ' ');
System.out.println(result);
I am creating a java method for this purpose with dynamic character
public String insertSpace(String myString,int indexno,char myChar){
myString=myString.substring(0, indexno)+ myChar+myString.substring(indexno);
System.out.println(myString);
return myString;
}
This is the same problem as joining together an array with commas. This version correctly produces spaces only between characters, and avoids an unnecessary branch within the loop:
String input = "Hello";
StringBuilder result = new StringBuilder();
if (input.length() > 0) {
result.append(input.charAt(0));
for (int i = 1; i < input.length(); i++) {
result.append(" ");
result.append(input.charAt(i));
}
}
public static void main(String[] args) {
String name = "Harendra";
System.out.println(String.valueOf(name).replaceAll(".(?!$)", "$0 "));
System.out.println(String.valueOf(name).replaceAll(".", "$0 "));
}
This gives output as following use any of the above:
H a r e n d r a
H a r e n d r a
One can use streams with java 8:
String input = "JAYARAM";
input.toString().chars()
.mapToObj(c -> (char) c + " ")
.collect(Collectors.joining())
.trim();
// result: J A Y A R A M
A simple way can be to split the string on each character and join the parts using space as the delimiter.
Demo:
public class Main {
public static void main(String[] args) {
String s = "JAYARAM";
s = String.join(" ", s.split(""));
System.out.println(s);
}
}
Output:
J A Y A R A M
ONLINE DEMO
Create a char array from your string
Loop through the array, adding a space +" " after each item in the array(except the last one, maybe)
BOOM...done!!
If you use a stringbuilder, it would be efficient to initalize the length when you create the object. Length is going to be 2*lengthofString-1.
Or creating a char array and converting it back to the string would yield the same result.
Aand when you write some code please be sure that you write a few test cases as well, it will make your solution complete.
I believe what he was looking for was mime code carrier return type code such as %0D%0A (for a Return or line break)
and
\u00A0 (for spacing)
or alternatively
$#032

Categories

Resources