Java String. Replace list of chars by other chars list - java

I have String variable with value- f.e.:
this is test-str-ing_łóśżćń.
And I would like replace this chars:
, -, ł,ó,ś,ż,ć,ń
with those:
_,_,l,o,s,z,c,n.
And I mean here, that if parser will found f.e.: char - (which is second in first list) should be replaced with char that is in the same position/place in second list, which in this example is: _.
The char ó should be replaced with char o.
The char ń should be replaced with char n.
In my case the list of characters to replace is quite long and parsing in loop for each char to replace would not be enought efficient.
I know method replaceAll(). but it only accept one in String and one out String
So I am looking for method, that will allow me to work on arrays/list of Strings instead of single String.
Please give me some help.

Use java.text.Normalizer to Decompose accented letters in base letter plus "combining diacritical marks."
String base = Normalizer.normalize(accented, Form.NFKD)
.replaceAll("\\p{M}", "");
This does a decompose (D) normalization, and then removes Marks.
Some replacements still needed.

char[] out = new char[src.length()];
for( j ...){
inputChar = src.charAt(j);
for (int i = 0; i < convertChars.length; i++) {
if (inputChar == convertChars[i]) {
inputChar = toChars[i];
}
}
}
out[j] = inputChar ;
}
out2 = new String(out);
Extracted from bigger code without IDE, not tested. Loop (I hope) don't allocate objects and should not degrade speed.

Make a static lookup table:
private static char[] substitutions = new char[65536];
static {
// Initialize
for (char c = 0; c < substitutions.length; c++) {
substitutions[c] = c;
}
// Now add mappings.
substitions['-'] = '_'; // Map source->target character
... // Add the rest
}
// LATER IN Code
char[] stringChars = inputString.toCharArray();
for (int i = 0; i < stringChars.length; i++) {
stringChars[i] = substitutions[stringChars[i]];
}
outputString = new String(stringChars);

Related

How to reverse a String after a comma and then print the 1st half of the String Java

For example String grdwe,erwd becomes dwregrdwe
I have most of the code I just have trouble accessing all of ch1 and ch2 in my code after my for loop in my method I think I have to add all the elements to ch1 and ch2 into two separate arrays of characters but I wouldn't know what to initially initialize the array to it only reads 1 element I want to access all elements and then concat them. I'm stumped.
And I'd prefer to avoid Stringbuilder if possible
public class reverseStringAfterAComma{
public void reverseMethod(String word){
char ch1 = ' ';
char ch2 = ' ';
for(int a=0; a<word.length(); a++)
{
if(word.charAt(a)==',')
{
for(int i=word.length()-1; i>a; i--)
{
ch1 = word.charAt(i);
System.out.print(ch1);
}
for (int j=0; j<a; j++)
{
ch2 = word.charAt(j);
System.out.print(ch2);
}
}
}
//System.out.print("\n"+ch1);
//System.out.print("\n"+ch2);
}
public static void main(String []args){
reverseStringAfterAComma rsac = new reverseStringAfterAComma();
String str="grdwe,erwd";
rsac.reverseMethod(str);
}
}
You can use string builder as described here:
First split the string using:
String[] splitString = yourString.split(",");
Then reverse the second part of the string using this:
splitString[1] = new StringBuilder(splitString[1]).reverse().toString();
then append the two sections like so:
String final = splitString[1] + splitString[0];
And if you want to print it just do:
System.out.print(final);
The final code would be:
String[] splitString = yourString.split(",");
splitString[1] = new StringBuilder(splitString[1]).reverse().toString();
String final = splitString[1] + splitString[0];
System.out.print(final);
Then, since you are using stringbuilder all you need to do extra, is import it by putting this at the top of your code:
import java.lang.StringBuilder;
It appears you currently have working code, but are looking to print/save the value outside of the for loops. Just set a variable before you enter the loops, and concatenate the chars in each loop:
String result = "";
for (int a = 0; a < word.length(); a++) {
if (word.charAt(a) == ',') {
for (int i = word.length() - 1; i > a; i--) {
ch1 = word.charAt(i);
result += ch1;
}
for (int j = 0; j < a; j++) {
ch2 = word.charAt(j);
result += ch2;
}
}
}
System.out.println(result);
Demo
Let propose a solution that doesn't use a StringBuilder
You should knoz there is no correct reason not to use that class since this is well tested
The first step would be to split your String on the first comma found (I assumed, in case there is more than one, that the rest are part of the text to reverse). To do that, we can you String.split(String regex, int limit).
The limit is define like this
If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n and the array's last entry will contain all input beyond the last matched delimiter.
If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Example :
"foobar".split(",", 2) // {"foobar"}
"foo,bar".split(",", 2) // {"foo", "bar"}
"foo,bar,far".split(",", 2) // {"foo", "bar,far"}
So this could be used at our advantage here :
String text = "Jake, ma I ,dlrow olleh";
String[] splittedText = text.split( ",", 2 ); //will give a maximum of a 2 length array
Know, we just need to reverse the second array if it exists, using the simplest algorithm.
String result;
if ( splittedText.length == 2 ) { //A comma was found
char[] toReverse = splittedText[1].toCharArray(); //get the char array to revese
int start = 0;
int end = toReverse.length - 1;
while ( start < end ) { //iterate until needed
char tmp = toReverse[start];
toReverse[start] = toReverse[end];
toReverse[end] = tmp;
start++; //step forward
end--; //step back
}
result = new String( toReverse ) + splittedText[0];
}
This was the part that should be done with a StringBuilder using
if ( splittedText.length == 2 ){
result = new StringBuilder(splittedText[1]).reverse().toString() + splittedText[0];
}
And if there is only one cell, the result is the same as the original text
else { //No comma found, just take the original text
result = text;
}
Then we just need to print the result
System.out.println( result );
hello world, I am Jake

Comparing string character by character in Java

How to compare individual character that is stored in a variable in Java?
String value = "abaabb";
Now how can I know that abaabb consist of only a and b in it and no other characters like c, d, ...
For this I want a way to compare individual characters in abaabb.
You can use .charAt() method:
String x="aabbbb";
for (int i = 0; i < x.length(); i++) {
if(x.charAt(i)=='a' || x.charAt(i)=='b') {
System.out.println("a or b");
}
}
You could use String#matches with Regular Expression:
boolean valid = "abaabb".matches("[ab]+");
easiest solution:
String value = "abaabb";
Set<Character> letters = new HashSet<Character>();
for(int i = 0; i < value.length(); i++){
letters.add(value.charAt(i));
}
//Edit
#Trincot
In set we collect unique characters in string, then we can build second collection with letters to check if only 'a' and 'b' are present
Set<Character> check = new HashSet<>();
check.add('a');
check.add('b');
letters.removeAll(check);
System.out.println(letters.isEmpty());

Counting the number of unique letters in a string

I have to write code that counts how many unique letters are in a string:
e.g
"aabbcdefff"
This will return 6 as there are 6 different letters in the string. Currently I have the code:
String letters = ("aabbcdefff");
char temp = ' ';
for (int i = 0; i < letters.length(); i++){
temp = inp.charAt(i);
if (temp != ' ') { //doesnt count spaces as letters
alphabetSize = alphabetSize+1;
for (int j = 0; j < inp.length(); j++){
tempInp = tempInp.replace(temp,' ');
}
}
}
The idea of this code is that it should when detecting a letter, replace all instances of it with a space. When i run this code however, it just gives me the length of the string. What am i doing wrong? Is there another more elegant way to do this?
Thanks for your help.
You are fine by just using a Set.
Loop over your string, and add each letter to your set. afterwards, check length of your set, and your done.
It's a one-liner with Java 8 streaming API:
long numberOfDistinctChars = s.chars().distinct().count()
You can easily find it using Linq service.
Please add using System.Linq; Namespace.
string str = "TestTest";
int cnt = str.ToLower().ToCharArray().Where(w => w != ' ').Distinct().Count();
You can do it easily by using Java collection (Set).
Set<Character> result = new HashSet<Character>();
String letters = ("aabbcdefff");
for (int i = 0; i < letters.length(); i++){
result.add(letters.charAt(i));
}
Your final result is in result set and it is always unique.
Reference: http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Thanks.
One way of doing this would be converting the string to an array and then using the following method:
String s = "aabbcdefff";
char[] charArray = s.toCharArray();
ArrayList<Character> al = new ArrayList<Character>();
for(char c : charArray){
if(al.contains(c)){
al.remove((Character)c);
}else{
al.add(c);
}
}
What ever is left in the array list 'al' are duplicates. The advantage of this method is that it has O(n) runtime

Replacing an unknown pattern size with a character

Is there a way to replace a specific repetitive character using regular expressions?
Example:
str = "Anne has nnnn things"
The solution would be:
"Ane has n things"
If a string has two or more instances of one character next to each other, the regular expression should replace them all with just one.
It is possible:
inputString.replaceAll("(.)\\1+", "$1")
Match one character, capture it, repeat it once or more, replace with only the capture.
However this may not be the faster solution. Such a thing is also doable with a simple loop:
public String removeRepetitions(final String input)
{
if (input.isEmpty())
return input;
final int len = input.length();
final StringBuilder sb = new StringBuilder(length);
char current = input.charAt(0);
char c;
sb.append(current);
for (int i = 1; i < len; i++) {
c = input.charAt(i);
if (c != current) {
sb.append(c);
current = c;
}
}
return sb.toString();
}
This should match n that repeats 2 or more times:
/n{2,}/

I want to read a String sentence from a Textfield and compare each letter in the String to my list

I want to read a String sentence from a Textfield and compare each letter in the String to my list of already made strings which look like this:
A = 123f;
B = 221d;
H = 2333gg;
And so on..
My question is: how can i read my message as individual strings lets say this is the message: "Hello World"
i want to be able to compare every word to my strings that i have made:
so "Hello World" it would compare the first letter "H" and it would make it into what i defined "H" to be, So it would output in a JLabel or anything else as 2333gg.
Thank you in advance!
I think you need to store your letters (A = ..., B = ..., H = ...) into a Map, then you iterate through the input letters (that you can get from the input string using toCharArray()), and if the Map contains the letter as a key, you output the corresponding value. Something like this:
Map<Character, String> lettersMap = new HashMap<Character, String>();
lettersMap.put(Character.valueOf('A'), "123f");
lettersMap.put(Character.valueOf('B'), "221d");
lettersMap.put(Character.valueOf('H'), "2333gg");
String input = "Hello world";
StringBuffer sb = new StringBuffer();
char[] inputLetters = input.toCharArray();
for (int i = 0; i < inputLetters.length; i++) {
Character letter = Character.valueOf(inputLetters[i]);
if (lettersMap.containsKey(letter))
sb.append(lettersMap.get(letter));
}
System.out.println(sb.toString());
Once you have a String (let's call it myString), you can iterate through the letters like so:
for (final char c : new StringIterator(myString))
{
// Do something with each character (c)
}
Does that help?
Edit: I'm SO sorry - I was using a non standard library in a piece of code and forgot.
How about:
for (int i = 0; i < myString.length(); i++)
{
char c = myString.charAt(i);
//Process char
}
You can use String.toCharArray() to get an array of chars, where you can access each char individually.
String[] charArray = userInput.toCharArray();
for (int i = 0; i < charArray.length; i++)
{
...
}

Categories

Resources