deleting special characters from a string - java

okay.
this is my first post here and I'm kind of new to java
so my question is simple :
is there any instruction in java that remove special characters from a string ?
my string should be only letters
so when the user enters a spacebar or a point or whatever that isn't a letter
it should be removed or ignored
well my idea was about making an array of characters and shift letters to the left each time there is something that isn't a letter
so I wrote this code knowing that x is my string
char h[]=new char [d];
for (int f=0;f<l;f++)
{
h[f]=x.charAt(f);
}
int ii=0;
while (ii<l)
{
if(h[ii]==' '||h[ii]==','||h[ii]=='-'||h[ii]=='\\'||h[ii]=='('||h[ii]==')'||h[ii]=='_'||h[ii]=='\''||h[ii]=='/'||h[ii]==';'||h[ii]=='!'||h[ii]=='*'||h[ii]=='.')
{
for(int m=ii;m<l-1;m++)
{
h[m]=h[m+1];
}
d=d-1;
ii--;
}
ii++;
}
well this works it removes the special char but I can't include all the exceptions in the condition I wonder if there is something easier :)

As others have said Strings in Java are immutable.
One way to catch all characters you do not want is to only allow the ones you want:
final String input = "some string . ";
final StringBuffer sb = new StringBuffer();
final String permittedCharacters = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (char c : input.toCharArray()){
if (permittedCharacters.indexOf(c)>=0){
sb.append(c);
}
}
final String endString = sb.toString();

Short answer - No, String is immutable. But you can use StringBuffer instead. This c ass contains deleteCharAt(int) method, that can be useful.

Related

Replace characters and keep only one of these characters

Can someone help me here? I dont understand where's the problem...
I need check if a String have more than 1 char like 'a', if so i need replace all 'a' for a empty space, but i still want only one 'a'.
String text = "aaaasomethingsomethingaaaa";
for (char c: text.toCharArray()) {
if (c == 'a') {
count_A++;//8
if (count_A > 1) {//yes
//app crash at this point
do {
text.replace("a", "");
} while (count_A != 1);
}
}
}
the application stops working when it enters the while loop. Any suggestion? Thank you very much!
If you want to replace every a in the string except for the last one then you may try the following regex option:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", " ");
somethingsomething a
Demo
Edit:
If you really want to remove every a except for the last one, then use this:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", "");
You can also do it like
String str = new String ("asomethingsomethingaaaa");
int firstIndex = str.indexOf("a");
firstIndex++;
String firstPart = str.substring(0, firstIndex);
String secondPart = str.substring(firstIndex);
System.out.println(firstPart + secondPart.replace("a", ""));
Maybe I'm wrong here but I have a feeling your talking about runs of any single character within a string. If this is the case then you can just use a little method like this:
public String removeCharacterRuns(String inputString) {
return inputString.replaceAll("([a-zA-Z])\\1{2,}", "$1");
}
To use this method:
String text = "aaaasomethingsomethingaaaa";
System.out.println(removeCharacterRuns(text));
The console output is:
asomethingsomethinga
Or perhaps even:
String text = "FFFFFFFourrrrrrrrrrrty TTTTTwwwwwwooo --> is the answer to: "
+ "The Meeeeeaniiiing of liiiiife, The UUUniveeeerse and "
+ "Evvvvverything.";
System.out.println(removeCharacterRuns(text));
The console output is........
Fourty Two --> is the answer to: The Meaning of life, The Universe and Everything.
The Regular Expression used within the provided removeCharacterRuns() method was actually borrowed from the answers provided within this SO Post.
Regular Expression Explanation:

how to replace letters by loop in java?

I am writing a cryptography program that converts the ciphertext to plaintext. By the letter's frequency, I manually crack all the cipher's letters to plaintext, and there is no patterns, so I need to write a loop that contains 26 times, to convert every single letter in the string to another letter.
My first try is using the replace statement in java,
which will be like this
str=str.replaceAll("A","E");
The question is, for instance, I input a string like this abc
and my key will be like this "replace a with c, replace b with p, replace c with q".
The output I want should be cpq, but the output I got is qpq.
Which means I want it be like one time convert.
So I am trying to use the loop, using the if
The way I am doing it is:
for (i=1;i<string.length;i++)
if (char[i]=="a")
char [i] ="b";
The error tells me that I can't convert string to char.
And also, I want to ask if I put the other 25 if statements inside this statement or pararall them?
To answer the second part of your question: I would not add 25 single if statements in your loop but instead use a Map<Character, Character> to store your replacements.
A complete solution could look like this:
public static void main(String[] args) {
Map<Character, Character> replacements = new HashMap<>();
replacements.put('a', 'c');
replacements.put('b', 'p');
replacements.put('c', 'q');
String input = "abcd";
StringBuilder output = new StringBuilder();
for (Character c : input.toCharArray()) {
output.append(replacements.getOrDefault(c, c));
}
System.out.println(output.toString());
}
This will keep characters you don't have a replacement for. Output:
cpqd
You can solve this as :
String str = "abc";
char [] ch = str.toCharArray();
for(int i=0; i<str.length(); i++){
if('a'==str.charAt(i)){
ch[i] = 'c';
}
if('b'==str.charAt(i)){
ch[i] = 'p';
}
if('c'==str.charAt(i)){
ch[i] = 'q';
}
}
System.out.println(String.valueOf(ch));
You can't convert a String to a char. So you need to either use all Strings or all chars. Instead of using the double quotes for String you could use the single quotes for char like this:
char[i]=='b'
and
char[i] = 'b';
Also instead of using a long if/else statement you could either use a switch statement, or even better you could create and use a Map to store the conversions in key/value pairs.

Split the String by \ which contains following string "abc\u12345. "

Before posting I tried using string split("\u") or \\u or \u it does not work, reason being is that \u is considered as unicode character while in this case it's not.
as already mentioned \u12345 is a unicode character and therefore handled as a single symbol.
If you have these in your string its already too late. If you get this from a file or over network you could read your input and escape each \ or \u you encounter before storing it in your string variable and working on it.
if you elaborate the context of your task a little more, perhaps we could find other solutions for you.
Java understands it as Unicode Character so, right thing to do will be to update the source to read it properly and avoid passing Unicode to java if not needed. One workaround way could be to convert the entire string into a character Array and check if character is greater than 128 and if yes, I append the rest of the array in a seperate StringBuilder. See of it below helps :
public static void tryMee(String input)
{
StringBuilder b1 = new StringBuilder();
StringBuilder b2 = new StringBuilder();
boolean isUni = false;
for (char c : input.toCharArray())
{
if (c >= 128)
{
b2.append("\\u").append(String.format("%04X", (int) c));
isUni = true;
}
else if(isUni) b2.append(c);
else b1.append(c);
}
System.out.println("B1: "+b1);
System.out.println("B2: "+b2);
}
Try this. You did not escape properly
split("\\\\u")
or
split(Pattern.quote("\\u"))
import java.util.Arrays;
public class Example {
public static void main (String[]args){
String str = "abc\u12345";
// first replace \\u with something else, for example with -u
char [] chars = str.toCharArray();
StringBuilder sb = new StringBuilder();
for(char c: chars){
if(c >= 128){
sb.append("-u").append(Integer.toHexString(c | 0x10000).substring(1) );
}else{
sb.append(c);
}
}
String replaced = sb.toString();
// now you can split by -u
String [] splited = sb.toString().split("-u");
System.out.println(replaced);
System.out.println(Arrays.toString(splited));
}
}

How to print a letter of a word using a number?

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();
}

How do I tell java to stop the loop at a certain character in a string?

So if i have a method where a string is entered and has a hyphen. like "cool*boy" if i want java to make a new string that starts out at the end of that string and prints each letter backward and continues until it reaches the asterisk and then goes forward and prints all the letters after the asterisk again so in the cool*boy example it's "yobboy" or high*school would be "loohcsschool" ... how would I do this. Thank you.
to JUST get everything up to the asterisk sign (which isn't working) I put,
int i;
String newStr = "";
for(i=s.length()-1; i >= s.charAt('*'); i--)
newStr = newStr + s.charAt(i);
I'm guessing you're not allowed to make that condition in the for loop. But I just don't get how you would do it. Please help thanks!
Change the condition to
s.charAt(i) != '*'
The simplest way to do this would be to use a substring instead of a loop.
String forward = s.substring(s.indexOf('*')+1);
String reverse = new StringBuilder(forward).reverse().toString();
return reverse+forward;
not tested codes:
String s = "high*school";
String newString = "";
String[] arr = s.split("[*]");
if (arr.length == 2) {
newString = new StringBuilder(arr[1]).reverse().toString() + arr[1];
}else{
... if the string has no (or more than one) "*"...
handle it if it is reqired.
}
Don't reinvent the wheel. Apache Commons StringUtils library:
substringBefore(String str, String separator)
substringAfter(String str, String separator)
reverse(String str)
Link: http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/index.html

Categories

Resources