I want to add space after every two chars in a string.
For example:
javastring
I want to turn this into:
ja va st ri ng
How can I achieve this?
You can use the regular expression '..' to match each two characters and replace it with "$0 " to add the space:
s = s.replaceAll("..", "$0 ");
You may also want to trim the result to remove the extra space at the end.
See it working online: ideone.
Alternatively you can add a negative lookahead assertion to avoid adding the space at the end of the string:
s = s.replaceAll("..(?!$)", "$0 ");
//Where n = no of character after you want space
int n =2;
StringBuilder str = new StringBuilder("ABCDEFGHIJKLMNOP");
int idx = str.length() - n;
while (idx > 0){
str.insert(idx, " ");
idx = idx - n;
}
return str.toString();
Explanation, this code will add space from right to left:
str = "ABCDEFGH" int idx = total length - 2; //8-2=6
while (8>0)
{
str.insert(idx, " "); //this will insert space at 6th position
idx = idx - n; // then decrement 6-2=4 and run loop again
}
The final output will be
AB CD EF GH
I wrote a generic solution for this...
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(2, "javastring", ' ');
System.out.println(result);
Related
(Java) How can I count the number of tab and space before the first character of a string
Assume that a string
String line = " Java is good."
There are totally 10 spaces in this string.
However, how can I count the number of tab and space before the first character "J" only?
There are 8 spaces before the first character "J" only.
How about:
String s = " Java is good.";
int total = 0;
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
total++;
} else {
break;
}
}
System.out.println(total);
Or
String s = " Java is good.";
int total = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == ' ' || ch == '\t') {
total++;
} else {
break;
}
}
System.out.println(total);
We can use a regex replacement length trick here:
String line = "\t \t Java is good.";
int numSpaces = line.length() - line.replaceAll("^[\t ]+", "").length();
System.out.println(numSpaces); // 7
For a project which uses the Guava library, the CharMatcher class can determine this:
int count = CharMatcher.noneOf(" \t").indexIn(line);
If the string does not contain a non-space, non-tab character, -1 is returned. Depending on the desired behavior, this special value can be checked for and an appropriate value returned.
For a project which uses the StreamEx library, the IntStreamEx.indexOf() method can determine this:
long count = IntStreamEx.ofChars(line).indexOf(c -> c != ' ' && c != '\t')
.orElse(line.length());
If the string does not contain a non-space, non-tab character, the length of the string is returned. This behavior can be changed by returning a different value from .orElse or otherwise changing how the OptionalLong value is accessed.
There is a trim method which removes leading and trailing whitespaces.
If you were positive there was only leading whitespace and not trailing, you could compare the length of the non-trimmed with the trimmed.
`
int diff = line.length - line.trim().length;
`
Or just count with a for loop
`
int spaces = 0;
for(int x = 0; x < line.length; x++){
if(line[x].equals(" ")){
spaces++;
}else break;
}
`
In the n integer where n = 1237534 (for example) I have to delete digit 3 so I can get the biggest value possible. n can be negative number also.
I can get 127534 or 123754.
The bigger is of course 127534, but how can I return it?
I've tried something like this:
int n = 1237534;
String newNum = String.valueOf(n);
int[] newGuess = new int[newNum.length()];
for (int i = 0; i < newNum.length(); i++) {
newGuess[i] = newNum.charAt(i) - '0';
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < newGuess.length; i++) {
if (!(newGuess[i] % 3 == 0)) {
sb.append(newGuess[i]);
}
}
System.out.println(sb);
I get 12754 which is not correct answer. Anyone maybe have an idea how to solve it?
This does not require arrays nor loops:
int n = 1237534;
String newNum = String.valueOf(n);
char c = '3';
StringBuilder sb1 = new StringBuilder( newNum );
StringBuilder sb2 = new StringBuilder( newNum );
int newGuess1 = Integer.parseInt(sb1.deleteCharAt(newNum.indexOf(c)).toString());
int newGuess2 = Integer.parseInt(sb2.deleteCharAt(newNum.indexOf(c, newNum.indexOf(c)+1)).toString());
System.out.println( newGuess1 > newGuess2 ? newGuess1: newGuess2 );
Here is an alternative approach that also checks to ensure that the number actually contains the digit. Otherwise, an exception could be thrown if the index returns -1.
The method simply deletes the first or last occurrence of the digit depending on whether the number is negative or not.
int n = 1234321;
int bad_digit = 3;
StringBuilder sb = new StringBuilder(Integer.toString(n));
String bad = Integer.toString(bad_digit);
int idxOfFirst = sb.indexOf(bad);
// first, make certain the number contains the digit.
if (idxOfFirst >= 0) {
if (sb.charAt(0) == '-') {
// if negative, delete last character to give the larger value
sb.deleteCharAt(sb.lastIndexOf(bad));
} else {
// else delete the first character to give the larger value
sb.deleteCharAt(idxOfFirst);
}
}
System.out.println(sb);
This prints the string rather than convert to an integer since printing an integer results in conversion to a string anyway. If the digit does not appear in the original number, then the original is printed. You can alter that handling to meet your requirements.
How about this:
int n = 123454321;
int bad_digit = 3;
StringBuilder s = new StringBuilder(n + "");
s.reverse();
System.out.println("Reversed String: " + s);
for (int i = 0; i < s.length(); i++) {
// Check if the character at index 'i' and the
// digit are equal, by converting both to strings
if (("" + s.charAt(i)).equals("" + bad_digit)) {
s.replace(i, i + 1, "");
break;
}
}
System.out.println("Reversed String after removing the digit (if found): " + s);
s.reverse();
System.out.println("Greatest number without the bad digit: " + s);
Basically, we need to remove the last occurrence of the digit to be removed (the bad_digit). So we convert the number to a string and reverse it. Now we need to remove the first occurrence of the digit. So we iterate over the characters, and when we find that digit, we remove it from the string, and exit the loop. Now we reverse the string again, and the output is what you want.
I thought typecasting to char we do the trick but it just prints ascii values
String str = JOptionPane.showInputDialog("Enter a word");
str = str.toUpperCase();
String temp = "";
for(int i = 0 ; i < str.length() ; i++)
{
temp += (char)str.charAt(i) + 1;
}
System.out.println(temp);
Your mistake is you are adding integer 1 to char .
This will return the ASCII code of the next char.
Change to
temp += (char)(str.charAt(i) +1)
You are adding + 1 and that is causing it to be converted to integer I am not sure if explained properly just remove it
I'm currently working on a problem in code hunt level 6.02 which asks me to capitalize every other letter in a String. I have tried doing it with toCharArray + StringBuilder in for loops. It works, but it's not good enough. I still can't get the perfect score for the problem. I'm running out of ideas. Any help will be greatly appreciated.
Note: This is my first post on stack overflow. So if I miss anything or ask question in a wrong way. Pls feel free to point it out for me. Thx.
s is the input string
Attempt 1:
char [] words = s.toCharArray();
for (int i = 0; i < words.length; i +=2){
words[i] = Character.toUpperCase(words[i]);
}
return new String(words);
Attempt 2:
StringBuilder result = new StringBuilder(s);
for (int i = 0; i < result.length(); i +=2){
result.replace(i, i + 1, result.substring(i,i + 1).toUpperCase());
}
return result.toString();
Input: "iaiaa"
Expected output: "IaIaA"
In both of your attempts, you're going through the characters 2 1/2 times.
Taking your second attempt;
StringBuilder result = new StringBuilder(s);
for (int i = 0; i < result.length(); i +=2){
result.replace(i, i + 1, result.substring(i,i + 1).toUpperCase());
}
return result.toString();
The first line copies all the characters, and your last line copies all the characters. Your for loop goes through half the characters, for a total of 2 1/2 sets of characters.
I don't know if this is faster, but here's my attempt.
String r = "";
for (int i = 0; i < s.length; i++) {
if (i % 2 == 0) {
r += s.substring(i, i + 1).toUpperCase();
} else {
r += s.substring(i, i + 1);
}
}
return r;
I realize that this looks like a lot of intermediate Strings are created, but string concatenation has improved since Java 1.7.
I don't know how efficient this really is, but this does the trick for capitalizing the first letter and every other letter after.
String sentence = "i want to manipulate this string";
char[] array = new char[] {};
array = sentence.toCharArray(); //put the sentence into a character array
for (int i = 0; i < array.length; i += 2) {
if (array[i] == ' ') { //if the character is blank, move to the next index
i++;
}
array[i] = Character.toUpperCase(array[i]); //capitalize
}
sentence = new String(array); //revert array back to String
System.out.println(sentence); //display
I'm doing a project for Java 1, and I'm completely stuck on this question.
Basically I need to double each letter in a string.
"abc" -> "aabbcc"
"uk" -> "uukk"
"t" -> "tt"
I need to do it in a while loop in what is considered "Java 1" worthy. So i'm guessing that this means more of a problematic approach.
I know that the easiest way for me to do this, from my knowledge, would be using the charAt method in a while loop, but for some reason my mind can't figure out how to return the characters to another method as a string.
Thanks
[EDIT] My Code (wrong, but maybe this will help)
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index);
index++;
}
String s="mystring".replaceAll(".", "$0$0");
The method String.replaceAll uses the regular expression syntax which is described in the documentation of the Pattern class, where we can learn that . matches “any character”. Within the replacement, $number refers to numbered “capturing group” whereas $0 is predefined as the entire match. So $0$0 refers to the matching character two times. As the name of the method suggests, it is performed for all matches, i.e. all characters.
Yeah, a for loop would really make more sense here, but if you need to use a while loop then it would look like this:
String s = "abc";
String result = "";
int i = 0;
while (i < s.length()){
char c = s.charAt(i);
result = result + c + c;
i++;
}
You can do:
public void doubleString(String input) {
String output = "";
for (char c : input.toCharArray()) {
output += c + c;
}
System.out.println(output);
}
Your intuition is very good. charAt(i) will return the character in the string at location i, yes?
You also said you wanted to use a loop. A for loop, traversing the length of the list, string.length(), will allow you to do this. At every single node in the string, what do you need to do? Double the character.
Let's take a look at your code:
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index); //return ends the method
index++;
}
Problematically for your code, you are returning two characters immediately upon entering the loop. So for a string abc, you are returning aa. Let's store the aa in memory instead, and then return the completed string like so:
int index = 0;
int length = str.length();
String newString = "";
while (index < length) {
newString += str.charAt(index) + str.charAt(index);
index++;
}
return newString;
This will add the character to newString, allowing you to return the entire completed string, as opposed to a single set of doubled characters.
By the way, this may be easier to do as a for loop, condensing and clarifying your code. My personal solution (for a Java 1 class) would look something like this:
String newString = "";
for (int i = 0; i < str.length(); i++){
newString += str.charAt(i) + str.charAt(i);
}
return newString;
Hope this helps.
try this
String a = "abcd";
char[] aa = new char[a.length() * 2];
for(int i = 0, j = 0; j< a.length(); i+=2, j++){
aa[i] = a.charAt(j);
aa[i+1]= a.charAt(j);
}
System.out.println(aa);
public static char[] doubleChars(final char[] input) {
final char[] output = new char[input.length * 2];
for (int i = 0; i < input.length; i++) {
output[i] = input[i];
output[i + 1] = input[i];
}
return output;
}
Assuming this is inside a method, you should understand that you can only return once from a method. After encountering a return statement, the control goes back to the calling method. Thus your approach of returning char every time in a loop is faulty.
int index = 0;
int length = str.length();
while (index < length) {
return str.charAt(index) + str.charAt(index); // only the first return is reachable,other are not executed
index++;
}
Change your method to build a String and return it
public String modify(String str)
{
int index = 0;
int length = str.length();
String result="";
while (index < length) {
result += str.charAt[index]+str.charAt[index];
index++;
}
return result;
}