I have look into most of questions but I couldn't find how to uppercase or lowercase specific character inside a word.
Example:
String name = "Robert"
What if I would like to make "b" Uppercase and rest lowercase also how to make first letter Uppercase and rest lowercase?
Like "john" >> Output >> "John"...
I have toUppercase() and toLowercase(). They convert the whole text.
Also I tried to include charAt but never worked with me.
You will need to take your string, take a substring of the specific character or characters you want to capitalize or lowercase, and then build a new string off of it.
Example
String test = "JoHn"; //make the H lowercase
test = test.substring(0,2) + test.substring(2,3).toLowercase() + test.substring(3);
The first substring gets all characters before the desired point, the second gets the desired character and lowercases it, and the final substring gets the rest of the string
You can use toCharArray() to capitalize the first letter like this:
String name = "robert";
// Convert String to char array.
char[] arr = name.toCharArray();
// Modify first element in array.
arr[0] = Character.toUpperCase(arr[0]);
String str = new String(arr);
System.out.println(str);
Output:
Robert
And you want to make "b" Uppercase and rest lowercase like this:
// Convert String to char array.
char[] arr2 = name.toCharArray();
// Modify the third element in array.
arr2[2] = Character.toUpperCase(arr2[2]);
String str2 = new String(arr2);
System.out.println(str2);
Output:
roBert
//Try this...
String str = "Robert";
for (int i = 0; i < str.length(); i++) {
int aChar = str.charAt(i);
// you can directly use character instead of ascii codes
if (aChar == 'b') {
aChar = aChar - 32;
} else if (aChar >= 'A' && aChar <= 'Z') {
aChar += 32 ;
}
System.out.print((char) aChar);
}
/*
Output will be- roBert
*/
I wouldn't use 'test.substring(2, 3).toLowerCase()' necessarily. 'Character.valueOf(test.charAt(2)).toUpperCase()' works. Also, the 'test.substring(0, 3)' is wrong; it should be 'test.substring(0, 2)'.
A function that capitalize the first letter
private String capitalize(String str) {
return Character.toUpperCase(str.charAt(0)) + str.substring(1);
}
A function that capitalize an arbitrary letter
private String replaceCharWithUpperCase(char letterToCapitalize, String str)
{
return str.replaceAll(letterToCapitalize, Character.toUpperCase(letterToCapitalize));
}
Then you can use the previous functions like that :
String a = "JOHN";
a = capitalize(a.toLowerCase());
// now a = John.
String b = "ROBERT";
a = replaceCharWithUpperCase('b', a.toLowerCase());
// now a = roBert.
Related
I have been set a task to convert each char in a string to * except for any spaces in that string (the string is user input), the one caveat is that I must use a for loop. My code is below... the current problem that I am having is that when I try to use the char in an if statement condition I am getting a "Type mismatch: cannot convert from char to Boolean" error. All help appreciated...
public static void main(String[] args) {
//declare vars
Scanner input = new Scanner(System.in);
String name = "";
int length = 0;
//get name string
System.out.println("Enter your name");
name = input.nextLine();
//get length of name string
length = name.length();
//convert name string to array of characters
char[] nameChars = name.toCharArray();
//iterate over array of chars replacing each
// char with * and space with space
for (int index=0;index==length;index++){
//if the char is a space then do nothing
if (nameChars[index] = ' ') {
//else convert to *
} else {
nameChars[index] = '*';
}
}
//convert array back to string and output
String newName = new String(nameChars);
System.out.println(newName);
//close resources
input.close();
}
Instead of writing all that code, try this:
String newName = name.replaceAll("\\S", "*");
The regex \S matches "any non whitespace character".
Use == in place of = for the if condition checking as == is the relational operator while = is the assignment operator.
Change index==length to index < length otherwise your loop will never run! Initially index = 0 while length is some positive value and index!=length then. So the loop will never run.
You have to use == instead of = like below:
if (yourChar == ' ') {
//your code ...
}
Try the below approach
if (nameChars[index] == ' ') {
//else convert to *
} else {
nameChars[index] = '*';
}
If you want to use your code, then your condition is wrong, you're affecting the space char to the current char if the string nameChars[index] = ' ' you must change it to nameChars[index] == ' ', note the double equal signe ==.
However, I suggest you use this simple condition, cause you'll not do anything when the current char is a space char, then you don't have to check if it's a space char:
if (nameChars[index] != ' ') {
nameChars[index] = '*';
}
Why do you want to invent a bicycle?
It's better to use the power of Java and exactly replaceAll method of String.class:
String input = "123 wer 456 zxcv!";
String result = input.replaceAll("[^ ]", "*");
System.out.println(result);
Java: how to convert each char in a string to '*' except for spaces
You can just do it in one line without any loops..
String str = pw.replaceAll("[^\\s]", "*");
TEST:
String str1 = "ASDAS sad!## !##^% ?".replaceAll("[^\\s]", "*");
System.out.println(str1);
OUTPUT:
***** ****** ***** *
Note: For char[], you can use String.valueOf(yourArray).replaceAll().
String text = "It is a string";
System.out.println(text.replaceAll("[a-zA-Z]", "*"));
Output for the code will be : ** ** * ******.
Note that it's easier to use a StringBuilder when you want to modify String. You need to remember that Strings are immutable.
I want to count how many special characters are there in my Character array.
This is my code so far:
String s = "hi .this :) is test +line";
int len = s.length();
Character[] array = new Character[len];
for (int i = 0; i < len ; i++)
{
if(array[i]==' ' || array[i]==':' || array[i]=='.' || array[i]=='\'' || array[i]=='\"' || array[i]==')')
special_chars++
}
You can use the methods of Character class.
if(!Character.isLetterOrDigit(array[i]) && !Character.isWhitespace(array[i]))
special_chars++;
Character.isLetterOrDigit checks if the char is a letter or a digit. If it is none, then it certainly is a special character!
Create a String of your special characters, loop through every character in your input, and check if it's in the String of special characters. Something like,
String s = "hi .this :) is test +line";
String spec = " :.'\")";
int special_chars = 0;
for (char ch : s.toCharArray()) {
if (spec.indexOf(ch) > -1) {
special_chars++;
}
}
Using a BitSet, you can efficiently set and check indexed binary information (in your case: whether a given character is special or not), so compared to other solutions in this thread you don't need to loop over the set of special characters:
BitSet specialCharacters = new BitSet();
specialCharacters.set(' ');
specialCharacters.set(':');
specialCharacters.set('.');
specialCharacters.set('\'');
specialCharacters.set('\"');
specialCharacters.set(')');
String text = "hi .this :) is test +line";
for (char c : text.toCharArray()) {
if (specialCharacters.get(c)) {
// special character detected
}
}
For example:
You're given a word and Set of letters. If the word contains letters that are not within the Set, then those letters are "replaced" with dashes. You're not actually supposed to change the given word, but create a new String that reflects those changes.
Say you were given a word: "magikarp". The Set contains the letters 'm', 'k', 'p'. The String that you would return would be "m---k--p".
How would you accomplish this by utilizing only a String and String methods? I also can't use any external libraries.
It is more intuitive to me to use arrays, but this has to be performed by building up a String instead of building any extra data structures for the sake of efficiency.
This is how I approached it (working solution but not done by building up a String), for further clarification:
public String getPattern (SortedSet<Character> guesses, String word) {
char[] pattern = word.toCharArray();
for (int i = 0; i < wordLength; i++) {
if (!guesses.contains(pattern[i])) {
pattern[i] = '-';
}
}
// Pads each character in the generated String with spaces and trims
// the leading and trailing spaces.
return new String(pattern).replace("", "").trim();
}
}
You can just use what String already provides, a method to get each character and a method to replace a specifc character with another:
public String getPattern (Set<Character> guesses, String word) {
for (int i=0; i<word.length(); ++i) {
char c = word.charAt(i);
if (!guesses.contains(c))
word = word.replace(c, '-');
}
return word;
}
Its not very efficient because it will create a new string instance for every character that needs to be replaced. For efficiency using a StringBuilder would be better.
How about building a regex String from the Set of characters, and using that as a param to the String.replaceAll method to return the filtered String?
Set<Character> letters = new HashSet<>();
letters.add('m');
letters.add('k');
letters.add('p');
String filter = "[^(";
for (Character letter : letters) {
filter += letter;
}
filter += ")]";
String toBeReplaced = "magikarp";
String result = toBeReplaced.replaceAll(filter, "-");
This is most certainly not the best way to approach the problem, except that it "builds up the String".
String newWord = "";
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
newWord = newWord + (
guesses.contains(c) ? c : '-'
);
}
This approach creates a new String instance on each letter rather than doing a quick replace. But it "builds it up".
I need to replace all commas after the 5th one. So if a String contains 10 commans, I want to leave only the first 5, and remove all subsequent commas.
How can I do this ?
String sentence = "Test,test,test,test,test,test,test,test";
String newSentence = sentence.replaceAll(",[6]","");
Just capture all the characters from the start upto the 5th comma and match all the remaining commas using the alternation operator |. So , after | should match all the remaining commas. By replacing all the matched chars with $1 will give you the desired output.
sentence.replaceAll("^((?:[^,]*,){5})|,", "$1");
DEMO
In case you were wondering how to solve this problem without using regular expressions... There are libraries that could make your life easier but here is the first thought that came to mind.
public String replaceSpecificCharAfter( String input, char find, int deleteAfter){
char[] inputArray = input.toCharArray();
String output = "";
int count = 0;
for(int i=0; i <inputArray.length; i++){
char letter = inputArray[i];
if(letter == find){
count++;
if (count <= deleteAfter){
output += letter;
}
}
else{
output += letter;
}
}
return output;
}
Then you would invoke the function like so:
String sentence = "Test,test,test,test,test,test,test,test";
String newSentence = replaceSpecificCharAfter(sentence, ',', 6);
I need a method that switches a letter from a specific index with another letter. Is there anything like it?
Like so:
String word = "test";
String letter = "e";
String secretWord = "????";
find the index of letter e and then find if e is in word. Then switch a "?" based on the index of the e in test.
So it would be ?e?? for secretWord.
You could use regex to search and replace any character that ISN'T letter:
String word = "test";
String secretWord = word.replaceAll("(?i)[^e]", "?");
You can also add more letters you don't want replaced to the regex (this would replace every non-vowel):
String secretWord = word.replaceAll("(?i)[^aeiouy]", "?");
Explanation of regex:
(?i) means "case-insensitive".
^ means "NOT".
aeiouy is the characters we DON'T want to match
Here's a demo of the regex replacement (just with e):
DEMO
string word = "test";
char letter = 'e';
string secretWord = "????";
int index = word.indexOf(letter);
if(index >= 0)
{
secretWord = secretWord.substring(0,index)+letter+secretWord.substring(index + 1);
System.out.println(secretWord);
}
This Code is for JAVA...... Try it
If you are using C# then try the Below coding.. It will help you
//Declare
string word = "test";
char letter = 'e';
string secretWord = "????";
if (word.IndexOf("e") != -1)//Find the Char is found or NOT
{
int index = word.IndexOf(letter); //Index of the Char
Console.WriteLine("Index of the Word E :" + word.IndexOf("e").ToString());
StringBuilder sb = new StringBuilder(secretWord);
sb[index] = letter; // Replacing the Char
secretWord = sb.ToString();
Console.WriteLine(secretWord);
}
I'd look at the task a bit differently. We have a secret ("test") and a way to display it, the result would be "????" or "?e??" if the letter e was provided. The sequence of ? is not a String itself but will be generated on demand. Then we don't have to replace something in a String (what we can't do, by the way, because strings are immutable). Here's the idea written in code:
public class SecretWord {
private String secret;
public SecretWord(String secret) {
this.secret = secret;
}
public String display(char c) {
if (secret == null) {
return "";
}
StringBuilder displayBuilder = new StringBuilder();
for (char secretChar : secret.toCharArray()) {
displayBuilder.append(secretChar == c ? c : '?');
}
return displayBuilder.toString();
}
}
I don't have enough rep to reply in a comment as yet, but you could expand on h2ooooo's post by adding in a variable to make it flexible, also:
String letter = "e";
String secretWord = word.replaceAll("(?i)[^" + letter + "]", "?");
+1, h2ooooo - tidy answer!
Westie