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
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.
As the title says, given a string, I would like to pad it (append) with n number of x character. Please see the below code. Is it possible to do that all in one String.format?
The commented line shows how to append n number of spaces; I would like to do the exact same thing with a custom character.
int paddingLength = (int) args.get(0);
String paddingItem = (String) args.get(1);
String temp = ((String) row.get(fieldName));
//temp = String.format("%-" + n + "s", s);
temp = String.format("%-" + paddingLength + "paddingItem", paddingItem + "temp", temp);
Example:
paddingLength: 5
paddingItem: "_"
temp = "test"
result: "test_____"
Another option is using StringBuilder.
Example.
int n = 5;
char x = '_';
String temp = "test";
StringBuilder paddedWord = new StringBuilder(temp);
for(int i=0; i<n; i++)
paddedWord.append(x);
Just remember to cast your StringBuilder back to a String if you are using it elsewhere .toString()
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 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);