I need to check if in my String "sir" i have some uppercase letters, if so, i need to assign the value of that letter to another string and then to delete the letter. my first part looks like this:
Pattern p = Pattern.compile("[^A-Z]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(sir);
boolean b = m.find();
so that i check if there is any uppercase letter, then i need to add assigning & deleting. i am not sure if this works. also i found
another way:
StringTokenizer stringTokenizer = new StringTokenizer(sir);
while (stringTokenizer.hasMoreTokens()) {
String a = stringTokenizer.nextToken();
if(a.equals(a.toUpperCase())) {
upper = a;
}
}
upper returns null everytime, even though sir = cL
does anyone know a way to:
get uppercase letter & positon from string
delete it
any help would be much appreciated.
To remove all UPPERCASE letters from a string:
String repl = sir.replaceAll("[A-Z]+", "");
To copy all UPPERCASE letters from a string to another string:
String upper = sir.replaceAll("[^A-Z]+", "");
This will give you all the capital letters in a string:
String inputString;
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
ouptutString += Character.isUpperCase(c) ? c + " " : "";
}
You can also try "guava" libriaries. There you can find set of classes for string manipulation. Among them CharMatcher (https://code.google.com/p/guava-libraries/wiki/StringsExplained#CharMatcher)
simple code example can be:
String string = "ABcdEFgh45";
String withoutUpperCase = CharMatcher.JAVA_UPPER_CASE.removeFrom(string);
//returns cdgh45
Related
I'm a student that is learning Java, and I have this code:
lletres = lletres.replace(lletres.charAt(2), codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));
lletres is a string, and it's like this
lletres = "BBB"
The result is "CCC" and I only want to change the last B, so the result can be like this: "BBC".
Reading the documentation for String.replace should explain what happened here (I marked the relevant part in bold):
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
One way to solve it is to break the string up to the parts you want and then put it back together again. E.g.:
lletres = lletres.substring(0, 2) + (char)(lletres.charAt(2) + 1);
As others pointed replace() will replace all the occurrences which matched.
So, instead you can make use of replaceFirst() which will accept the regx
lletres = lletres.replaceFirst( lletres.charAt( 2 ) + "$", (char) ( lletres.charAt( 2 ) + 1 ) + "" )
You could use StringBuilder for your purpose:
String lletres = "BBB";
String codi = "CCC";
StringBuilder sb = new StringBuilder(lletres);
sb.setCharAt(2, codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));
lletres = sb.toString();
If you need to change only the last occurrence in the string, you need to split the string into parts first. I hope following snippet will be helpful to you.
String lletres = "BBB";
int lastIndex = lletres.lastIndexOf('B');
lletres = lletres.substring(0, lastIndex) + 'C' + lletres.substring(lastIndex+1);
This code will find index of last letter B and stores it in lastIndex. Then it splits the string and replaces that B letter with C letter.
Please keep in mind that this snippet doesn't check whether or not the letter B is present in the string.
With slight modification you can get it to replace whole parts of the string, not only letters. :)
Try this one.
class Rplce
{
public static void main(String[] args)
{
String codi = "CCC";
String lletres = "BBB";
int char_no_to_be_replaced = 2;
lletres = lletres.substring(0,char_no_to_be_replaced ) + codi.charAt(codi.indexOf(lletres.charAt(char_no_to_be_replaced )) + 1) + lletres.substring(char_no_to_be_replaced + 1);
System.out.println(lletres);
}
}
use this to replace the last character
lletres = lletres.replaceAll(".{1}$", String.valueOf((char) (lletres.charAt(2) + 1)));
suppose you have dynamic value at last index and you want to replace that value will increasing one then use this code
String lletres = "BBB";
int atIndex = lletres.lastIndexOf('B');
char ReplacementChar = (char)(lletres.charAt(lletres.lastIndexOf('B'))+1);
lletres= lletres.substring(0, atIndex)+ReplacementChar;
System.out.println(lletres);
output
BBC
I'm relatively new to coding and my teacher asked us to make a code for a hangman game. He told us that we must accomplish this without the use of Arrays. My question is along the lines of this: If I have a String that is declared by the user and then a correct letter is guessed, how would I specifically be able to replace a substituted underscore with the guessed letter?
For example...
input is "cats"
system types "_ _ _ _"
say I typed the letter "a" and I want the output to be:
"_ a _ _"
How would I get the placement number of that letter and then manipulate the underscore to make it the letter?
StringBuilder.charAt()
StringBuilder.setCharAt()
You may want to have a look at these methods.
For the purpose of printing, you may want StringBuilder.toString().
You could use substrings. Something like this.
String original = "apple";
String guessed = original;
String withUnderscores = "_____";
String guess = "a";
while (guessed.contains(guess))
{
int index = guessed.indexOf(guess);
withUnderscores = withUnderscores.substring(0, index) + guess + withUnderscores.substring(index + 1);
guessed = guessed.substring(0, index) + "." + guessed.substring(index + 1);
}
System.out.println(original);
System.out.println(guessed);
Use one variable to store the underscore string. (ie "____"
Use another variable to store the answer string. (ie "cats").
Get the users input and and loop through the string taking the character at each index. If any variable matches the input letter (string1.equals(string2)) replace the character in the underscore string at whatever index your loop is at.
Use charAt() to get the character at a place in a string.
You can do this with a String or the StringBuilder class. If you haven't learned about StringBuilder in your classes, you probably shouldn't use it for your assignment.
Try something like this (I would prefer to have the guesses on a Set, it would be more clear than using a string to hold them):
public String maskUnguessedLetters(String answer, String guessed) {
Char MASKED = '_';
StringBuilder sb = new StringBuilder();
for (Char c : answer.toCharArray()) {
sb.append(guessed.contains(c.toString())
? c
: MASKED);
}
return sb.toString();
}
I don't completely understand the question, but I think this might help.
final String trueWord="cats";
String guessWord="____";
String input="a";
//if the input matches
if(trueWord.contains(input)){
//last Index of input in trueWord
int lastEntry=-1;
//hold all indices of input character in trueWord
ArrayList<Integer> indices=new ArrayList<>();
while(trueWord.indexOf(input,lastEntry+1) >= 0){
lastEntry=trueWord.indexOf(input);
indices.add(lastEntry);
}
//now replace the characters at the indices
StringBuilder newGuessWord = new StringBuilder(guessWord);
for(int index:indices){
//replace one character at a time.
newGuessWord.setCharAt(index, input.charAt(0));
}
//the new word
guessWord=newGuessWord.toString();
}
This is the not the most optimised code but will definitely give you an idea of how your task can be done.
public static void main(String[] args) {
final String word = "cats";
Scanner scanner = new Scanner(System.in);
System.out.println("Guess the character");
String finalString = "";
char letter = scanner.next().charAt(0);
for (char s : word.toCharArray()) {
if (s == letter) {
finalString += s;
} else
finalString += "_";
}
System.out.println(finalString);
scanner.close();
}
Let's say I have 2 strings and i need to calculate a difference between their unique characters. It's simple:
String s1 = "abcd";
String s2 = "aaaacccbbf";
//answer: 1
The answer is 1, because there is no "f" in s1 variable.
But what about characters like மா or 漢字, or any other non ASCII character? If i loop though those strings, one character like கு will count 2-3 times as separate character, giving me wrong answer:
String s1 = "ab";
String s2 = "aaaகுb";
//answer: 2 (wrong!)
The code i tried with:
class a {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sc.nextLine();
sc.close();
String missingCharacters= "";
for(char c : s2.toCharArray()) {
if(!missingCharacters.contains(c+"") && !s1.contains(c+""))
missingCharacters+= c;
}
System.out.println(missingCharacters.length());
}
}
Your symbol கு is compound form of Tamil script which contains two Unicode chars க் + உ (0B95 + 0BC1). If you plan to work with Tamil script you have to find all similiar characters with pattern:
String s1 = "ab";
String s2 = "aaaகுb";
Pattern pattern = Pattern.compile("\\p{L}\\p{M}*");
Matcher matcher = pattern.matcher(s2);
Set<String> missingCharacters=new TreeSet<>();
while (matcher.find()) {
missingCharacters.add(matcher.group());
}
matcher = pattern.matcher(s1);
while (matcher.find()) {
missingCharacters.remove(matcher.group());
}
System.out.println(missingCharacters.size());
Regex source:
How to Match a Single Unicode Grapheme
Set<Integer> missing = new HashSet<>();
for (int i = 0; i < s1.length();) {
int codePoint = s1.codePointAt(i);
if (s2.indexOf(codePoint) == -1) {
missing.add(codePoint); // takes care of duplicates
}
i += Character.charCount(codePoint);
}
System.out.println(missing.size());
கு is a special character, it it formed by merging க and ு, thus creating 2 different characters, and doesn't have 1 single char value. You are looping over the chars in s2, so you won't find that character itself.
Java doesn't have a way around this, as String.substring() and String.charAt() both use chars.
Conclusion, it's impossible to do this with Java's default libraries.
I want to replace all numbers inside a string with specific values.
Teststring: -SD12431;ABC333
How can I identify blocks of digits, and especially replace them with a (dynamic) new value?
For example after replacement:
-SDfirst;ABCsecond?
The replaceFirst() method will let you do this if you use it in a loop.
String myNewString = myString.replaceFirst("\\d+","first");
If you loop over the this statement, each invocation of replaceFirst() will replace the first group of digits with whatever you provide as a second argument.
You can do it this way
StringBuffer sb = new StringBuffer();
Matcher m = Pattern.compile("\\d+").matcher(str);
int n = 0;
while(m.find()) {
if (++n == 1) {
m.appendReplacement(sb, "first");
} else {
m.appendReplacement(sb, "second");
}
}
m.appendTail(sb);
s = sb.toString();
You can do something like this:
yourString = yourString.replaceFirst("\\d+",firstString).replaceFirst("\\d+",secondString); //and so on
or use a loop if it fits your needs better
You can use the replaceFirst(String regex, String replacement) function of the string class.
Look at
http://javarevisited.blogspot.fr/2011/12/java-string-replace-example-tutorial.html
So in first argument you have to use a regex for finding digit such as :
"[0-9]" will find a single digit
"[0-9]+" will find one or more digit
String testString = "-SD12431;ABC333";
ArrayList<String> remplaceBy= new ArrayList<String>();
remplaceBy.add("first");
remplaceBy.add("second");
remplaceBy.add("third");
String newString = testString;
String oldString ="";
int i =0;
while(!newString.equals(oldString))
{
oldString = new String(newString);
newString = newString.replaceFirst("[0-9]+",remplaceBy.get(i));
i++;
System.out.println("N1:"+newString);
System.out.println("O1:"+oldString);
}
System.out.println("New String"+newString);
I'm having problems with strings and I need a solution I'm trying to replace characters found at a certain position with a character found in also the same position for example
private String wordNormalize(String enteredWord,String dictionary){
String normalizedWord = null;
// remove empty spaces at beginning and at the end of the word and change to lower case
normalizedWord = enteredWord.trim().toLowerCase();
//normalize term, removing all punctuation marks
normalizedWord = normalizedWord.replaceAll("["+punctuationMarks2+"]", "[b,v]");
//normalize word removing to character if dictionary has english lang
normalizedWord = normalizedWord.replaceFirst("to ", " ");
//normalizeWord if dictionary has german
if(normalizedWord.length() > 0){
normalizedWord.replace("a,b,c","t,u,v");
/*for(int i = 0;i<normalizedWord.length();i++){
char currentChar = normalizedWord.charAt(i); // currently typed character
String s1= Character.toString(currentChar);
for(int j = 0;j<specialCharacters.length;j++){
s1.replaceAll("[ "+specialCharacters[i]+" ]",""+replaceCharactersDe[i]+"");
}
= str.replace("a,b,c","t,u,v");
}*/
}
//normalize term removing special characters and replacing them
/*for(int i = 0; i > specialCharacters.length;i++){
if(normalizedWord.equals(specialCharacters[i])){
normalizedWord = replaceCharactersDe[i];
}
}*/
return normalizedWord;
}
So if a user enters a its replaced with t and if a user enters b its replaced with u and if the user enters c it will be replaced with v and only in that order is this possible and if it is show me the right way its supposed to be done
It is not clear to me what you are trying to approach with
normalizedWord = normalizedWord.replaceAll("["+punctuationMarks2+"]", "[b,v]");
It does not seem right, but i don't know how to fix it because I don't know what it's trying to do. I guess what you are looking for is
normalizedWord = normalizedWord.replaceAll("\\p{Punct}", "");
On the other part you are doing nothing, because Strings are immutable. You want to do something like
normalizedWord = normalizedWord.replace("a,b,c","t,u,v");
but that would replace all occurrences of the substring "a,b,c" with the string "t,u,v"-
What you want is:
normalizedWord = normalizedWord.replace('a', 't');
normalizedWord = normalizedWord.replace('b', 'u');
normalizedWord = normalizedWord.replace('c', 'v');
We could work on a more general solution, but you have to show us how the dictionary , which is a String, is formatted.