When I run my code after I input this
1 qwertyuiopasdfghjklzxcvbnm
will
it still prints out will instead of replacing the characters like it should, why is that?
public static void main(String[] args)
{
String input="";
int cases= sc.nextInt();
String al= sc.next();
String upAl= al.toUpperCase();
char [] upAlph = upAl.toCharArray();
char[] alph = al.toCharArray();
for(int i=0; i<cases; i++)
{
input=sc.next();
input.replaceAll("a", ""+ alph[0]);
input.replaceAll("b", ""+ alph[1]);
input.replaceAll("c", ""+ alph[2]);
input.replaceAll("d", ""+ alph[3]);
input.replaceAll("e", ""+ alph[4]);
input.replaceAll("f", ""+ alph[5]);
input.replaceAll("g", ""+ alph[6]);
input.replaceAll("h", ""+ alph[7]);
input.replaceAll("i", ""+ alph[8]);
input.replaceAll("j", ""+ alph[9]);
input.replaceAll("k", ""+ alph[10]);
input.replaceAll("l", ""+ alph[11]);
input.replaceAll("m", ""+ alph[12]);
input.replaceAll("n", ""+ alph[13]);
input.replaceAll("o", ""+ alph[14]);
input.replaceAll("p", ""+ alph[15]);
input.replaceAll("q", ""+ alph[16]);
input.replaceAll("r", ""+ alph[17]);
input.replaceAll("s", ""+ alph[18]);
input.replaceAll("t", ""+ alph[19]);
input.replaceAll("u", ""+ alph[20]);
input.replaceAll("v", ""+ alph[21]);
input.replaceAll("w", ""+ alph[22]);
input.replaceAll("x", ""+ alph[23]);
input.replaceAll("y", ""+ alph[24]);
input.replaceAll("z", ""+ alph[25]);
input.replaceAll("A", upAlph[0]+"");
input.replaceAll("B", upAlph[1]+"");
input.replaceAll("C", upAlph[2]+"");
input.replaceAll("D", upAlph[3]+"");
input.replaceAll("E", upAlph[4]+"");
input.replaceAll("F", upAlph[5]+"");
input.replaceAll("G", upAlph[6]+"");
input.replaceAll("H", upAlph[7]+"");
input.replaceAll("I", upAlph[8]+"");
input.replaceAll("J", upAlph[9]+"");
input.replaceAll("K", upAlph[10]+"");
input.replaceAll("L", upAlph[11]+"");
input.replaceAll("M", upAlph[12]+"");
input.replaceAll("N", upAlph[13]+"");
input.replaceAll("O", upAlph[14]+"");
input.replaceAll("P", upAlph[15]+"");
input.replaceAll("Q", upAlph[16]+"");
input.replaceAll("R", upAlph[17]+"");
input.replaceAll("S", upAlph[18]+"");
input.replaceAll("T", upAlph[19]+"");
input.replaceAll("U", upAlph[20]+"");
input.replaceAll("V", upAlph[21]+"");
input.replaceAll("W", upAlph[22]+"");
input.replaceAll("X", upAlph[23]+"");
input.replaceAll("Y", upAlph[24]+"");
input.replaceAll("Z", upAlph[25]+"");
input.replaceAll("_", " ");
pw.println(input);
}
Strings are immutable. Assign input to the result of replaceAll:
input = input.replaceAll("a", ""+ alph[0]);
...
Aside: Consider using String#replace if regular expressions are not required.
Strings are immutable in java , you cannot modify strings after creating them, consider assigning the result of replaceAll to the original string
input = input.replaceAll("string", "string");
The method replaceAll returns a new string after replacement.
even += doesn't add the value to the string, it creates another string internally.Thus, consider using StringBuilder for better performance if you want to modify the string very often
I was coding this method by Friday, before leaving from job, but had to leave.
Anyhow, I did finish it today.
public static String replaceStringChars(String input, String abc, String replacement, boolean ignoreCase) {
abc = (ignoreCase ? abc.toLowerCase() : abc) + (ignoreCase ? abc.toUpperCase() : "") + "_";
replacement = (ignoreCase ? replacement.toLowerCase() : replacement) + (ignoreCase ? replacement.toUpperCase() : "") + " ";
input = input.replace(abc, replacement);
StringBuilder newString = new StringBuilder(input);
for (int a = 0; a < input.length(); a++) {
char chr = input.charAt(a);
int index = abc.indexOf(chr);
if (index >= 0) {
newString.setCharAt(a, replacement.charAt(index));
}
}
return newString.toString();
}
How to test it? :
public static void main(String [] args)
{
String input = "will_is_my_pastor";
String abc = "abcdefghijklmnopqrstuvwxyz";
String replacement = "qwertyuiopasdfghjklzxcvbnm";
System.out.println(abc);
System.out.println(replacement);
System.out.println(replaceStringChars(input, abc, replacement, true));
}
Related
I have the following Code:
#Test
public void testReplace(){
int asciiVal = 233;
String str = new Character((char) asciiVal).toString();
String oldName = "Fr" + str + "d" + str + "ric";
System.out.println(oldName);
String newName = oldName.replace("é", "_");
System.out.println(newName);
Assert.assertNotEquals(oldName, newName); // Its still equal. Howto Replace with a String
String notTheWayILike = oldName.replace((char) 233 + "", "_"); // I don't want to do this.
Assert.assertNotEquals(oldName, notTheWayILike);
}
How can I replace the character with a String ?
I need this, because they should be userfriendly defined as Strings or chars.
I have written the following function which gets rid of characters in a string that can't be represented in iso88591:
public static String convert(String str) {
if (str.length()==0) return str;
str = str.replace("–","-");
str = str.replace("“","\"");
str = str.replace("”","\"");
return new String(str.getBytes(),iso88591charset);
}
My problem is this doesn't have the behavior I require.
When it comes across a character that has no representation it is converted to multiple bytes. I want that character to be simply omitted from the result.
I would also like to somehow not have to have all those replace commands.
I have been researching charsetEnocder. It has methods like:
CharsetEncoder encoder = iso88591charset.newEncoder();
encoder.onMalformedInput(CodingErrorAction.IGNORE);
encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
which seem to be what I want, but I have failed to even write a function that mimics what I already have using charset encoder yet alone get to set those options.
Also I am restricted to Java 6 :(
Update:
I came up with a nasty solution for this, but there must be a better way to do it:
public static String convert(String str) {
if (str.length()==0) return str;
str = str.replace("–","-");
str = str.replace("“","\"");
str = str.replace("”","\"");
String str2 = "";
for (int c=0;c<str.length();c++) {
String cur = (new Character(str.charAt(c))).toString();
if (cur.equals(new String(cur.getBytes(),iso88591charset))) str2 += cur;
}
return new String(str2.getBytes(),iso88591charset);
}
One possibile way could be
// U+2126 - omega sign
// U+2013 - en dash
// U+201c - left double quotation mark
// U+201d - right double quotation mark
String str = "\u2126\u2013\u201c\u201d";
System.out.println("original = " + str);
str = str.replace("–", "-");
str = str.replace("“", "\"");
str = str.replace("”", "\"");
System.out.println("replaced = " + str);
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (c <= '\u00ff') {
sb.append(c);
}
}
System.out.println("stripped = " + sb);
output
original = Ω–“”
replaced = Ω-""
stripped = -""
There is some line, for example "1 qqq 4 aaa 2" and list {aaa, qqq}. I must change all words (consists only from letters) on words from list. Answer on this example "1 aaa 4 qqq 2". Try
StringTokenizer tokenizer = new StringTokenizer(str, " ");
while (tokenizer.hasMoreTokens()){
tmp = tokenizer.nextToken();
if(tmp.matches("^[a-z]+$"))
newStr = newStr.replaceFirst(tmp, words.get(l++));
}
But it's not working. In result I have the same line.
All my code:
String space = " ", tmp, newStr;
Scanner stdin = new Scanner(System.in);
while (stdin.hasNextLine()) {
int k = 0, j = 0, l = 0;
String str = stdin.nextLine();
newStr = str;
List<String> words = new ArrayList<>(Arrays.asList(str.split(" ")));
words.removeIf(new Predicate<String>() {
#Override
public boolean test(String s) {
return !s.matches("^[a-z]+$");
}
});
Collections.sort(words);
StringTokenizer tokenizer = new StringTokenizer(str, " ");
while (tokenizer.hasMoreTokens()){
tmp = tokenizer.nextToken();
if(tmp.matches("^[a-z]+$"))
newStr = newStr.replaceFirst(tmp, words.get(l++));
}
System.out.printf(newStr);
}
I think the problem might be that replaceFirst() expects a regular expression as first parameter and you are giving it a String.
Maybe try
newStr = newStr.replaceFirst("^[a-z]+$", words.get(l++));
instead?
Update:
Would that be a possibility for you:
StringBuilder _b = new StringBuilder();
while (_tokenizer.hasMoreTokens()){
String _tmp = _tokenizer.nextToken();
if(_tmp.matches("^[a-z]+$")){
_b.append(words.get(l++));
}
else{
_b.append(_tmp);
}
_b.append(" ");
}
String newStr = _b.toString().trim();
Update 2:
Change the StringTokenizer like this:
StringTokenizer tokenizer = new StringTokenizer(str, " ", true);
That will also return the delimiters (all the spaces).
And then concatenate the String like this:
StringBuilder _b = new StringBuilder();
while (_tokenizer.hasMoreTokens()){
String _tmp = _tokenizer.nextToken();
if(_tmp.matches("^[a-z]+$")){
_b.append(words.get(l++));
}
else{
_b.append(_tmp);
}
}
String newStr = _b.toString().trim();
That should work.
Update 3:
As #DavidConrad mentioned StrinkTokenizer should not be used anymore. Here is another solution with String.split():
final String[] _elements = str.split("(?=[\\s]+)");
int l = 0;
for (int i = 0; i < _tokenizer.length; i++){
if(_tokenizer[i].matches("^[a-z]+$")){
_b.append(_arr[l++]);
}
else{
_b.append(_tokenizer[i]);
}
}
Just out of curiosity, another solution (the others really don't answer the question), which takes the input line and sorts the words alphabetically in the result, as you commented in your question.
public class Replacer {
public static void main(String[] args) {
Replacer r = new Replacer();
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
System.out.println(r.replace(in.nextLine()));
}
}
public String replace(String input) {
Matcher m = Pattern.compile("([a-z]+)").matcher(input);
StringBuffer sb = new StringBuffer();
List<String> replacements = new ArrayList<>();
while (m.find()) {
replacements.add(m.group());
}
Collections.sort(replacements);
m.reset();
for (int i = 0; m.find(); i++) {
m.appendReplacement(sb, replacements.get(i));
}
m.appendTail(sb);
return sb.toString();
}
}
I want to convert a String Array to String so that later on while retrieving I can parse String to String[] with the help of (,) separator.
String [] ------------> String
//and later
String ---------------> String[]
Can someone guide on how to do this?
for (int i = 0; i <= count; i++) {
Log.d(TAG, "arrayData == " +arrayData[i]);
// Joining:
String joined = String.join(",", arrayData);
//This will give error "The method join(String, String[]) is undefined for the type String"
}
You can use String.join StringBuilder and String.split:
// Joining:
String joined = String.join(",", stringArr);
StringBuilder buffer = new StringBuilder();
for (String each : stringArr)
buffer.append(",").append(each);
String joined = buffer.deleteCharAt(0).toString();
// Splitting:
String[] splitted = joined.split(",");
In the input file, there are 2 columns: 1) stem, 2) affixes. In my coding, i recognise each of the columns as tokens i.e. tokens[1] and tokens[2]. However, for tokens[2] the contents are: ng ny nge
stem affixes
---- -------
nyak ng ny nge
my problem here, how can I declare the contents under tokens[2]? Below are my the snippet of the coding:
try {
FileInputStream fstream2 = new FileInputStream(file2);
DataInputStream in2 = new DataInputStream(fstream2);
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String str2 = "";
String affixes = " ";
while ((str2 = br2.readLine()) != null) {
System.out.println("Original:" + str2);
tokens = str2.split("\\s");
if (tokens.length < 4) {
continue;
}
String stem = tokens[1];
System.out.println("stem is: " + stem);
// here is my point
affixes = tokens[3].split(" ");
for (int x=0; x < tokens.length; x++)
System.out.println("affix is: " + affixes);
}
in2.close();
} catch (Exception e) {
System.err.println(e);
} //end of try2
You are using tokens as an array (tokens[1]) and assigning the value of a String.split(" ") to it. So it makes things clear that the type of tokens is a String[] array.
Next,
you are trying to set the value for affixes after splitting tokens[3], we know that tokens[3] is of type String so calling the split function on that string will yield another String[] array.
so the following is wrong because you are creating a String whereas you need String[]
String affixes = " ";
so the correct type should go like this:
String[] affixes = null;
then you can go ahead and assign it an array.
affixes = tokens[3].split(" ");
Are you looking for something like this?
public static void main(String[] args) {
String line = "nyak ng ny nge";
MyObject object = new MyObject(line);
System.out.println("Stem: " + object.stem);
System.out.println("Affixes: ");
for (String affix : object.affixes) {
System.out.println(" " + affix);
}
}
static class MyObject {
public final String stem;
public final String[] affixes;
public MyObject(String line) {
String[] stemSplit = line.split(" +", 2);
stem = stemSplit[0];
affixes = stemSplit[1].split(" +");
}
}
Output:
Stem: nyak
Affixes:
ng
ny
nge