Replace word in Java - java

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

Related

Create random word using StringBuilder - P

I am trying to create 10 lines of 3 words using a string builder and random. Currently, I have two loops but not producing what I want.
public String generateRandSentences() {
}
}
return strBuilder.toString();
}
try to do it step by step you can replace these line
String rGenCharSet = sentences[rGen.nextInt(sentences.length)];
strBuilder.append(rGenCharSet + " ");
to
int randomnumber = rGen.nextInt(sentences.length);
String rGenCharSet = sentences[randomnumber];
strBuilder.append(rGenCharSet + " ");
and then try to print the string builder in output
Note that println() prints a string builder, as in:
System.out.println(sb);
because sb.toString() is called implicitly, as it is with any other object in a println() invocation.
It generates one line of 75 characters because a line separator is never inserted. Try adding strBuilder.append('\n') after each sentence is generated as in:
public String generateRandSentences() {
String[] sentences = {"mum", "can", "you", "get", "one", "bun", "for",
"guy", "one", "for", "gus", "his", "old", "man", "who"};
StringBuilder strBuilder = new StringBuilder();
Random rGen = new Random();
for (int row = 0; row < 5; row++) {
for (int words = 0; words < 15; words++) {
String rGenCharSet = sentences[rGen.nextInt(sentences.length)];
strBuilder.append(rGenCharSet + " ");
}
strBuilder.append('\n');
}
return strBuilder.toString();
}
TextView txtView1 = findViewById(R.id.txtview_vc_1);
txtView1.setText(generateRandSentences());
import java.util.*;
class Main {
public static void main(String[] args){
generateRandSentences();
}
public static void generateRandSentences() {
Random rGen = new Random();
String[] sentences = {"mum", "can", "you", "get", "one", "bun", "for","guy", "one", "for", "gus", "his", "old", "man", "who"};
int size = sentences.length;
for(int i = 0 ; i < 5 ; i++)
{
StringBuilder strBuilder = new StringBuilder();
for(int j = 0 ; j < 15 ; j++)
{
String str = sentences[rGen.nextInt(size)];
strBuilder.append(str + " ");
}
System.out.println(strBuilder.toString());
}
}
}

Java code beautifier not giving last characters

I tried with this code to creates a code beautifier. But if it finds a "}", beautify is breaking. How can I fix it with this code?
String code = "class Demo{public static void main(String[] args) {System.out.println(\"ABC\");if(\"A\".equals(\"A\")){return \"A\";}System.out.println(\"ABC\");}}";
String outtext = code;
String repfrom = "{";
String repto = "{\n";
Pattern p = Pattern.compile(repfrom, Pattern.LITERAL);
Matcher m = p.matcher(outtext);
int counter = 0;
StringBuffer sb = new StringBuffer();
while (m.find()) {
counter++;
m.appendReplacement(sb, repto + (tab += "\t"));
}
m.appendTail(sb);
String newtext = sb.toString().replace(";", ";\n" + tab);
String replace = "";
for (int i = 0; i < counter; i++) {
replace = newtext.replace("}", "\b}");
}
System.out.println(replace);
My output is:
class Demo{
public static void main(String[] args) {
System.out.println("ABC");
if("A".equals("A")){
return "A";
}System.out.println("ABC");
}

Java StringTokenizer

I have the following input
(11,C) (5,) (7,AB)
I need to split them into 2 part for each coordinates.
So my intarray should have 11, 5, 7
and my letter array should have C,,AB
But when I try using stringtokenizer,
I only get my intarray should have 11, 5, 7
and my letter array should have C,AB
Is there any way I could get the empty part of (5,)?
Thank you.
Vector<String> points = new Vector<String> ();
String a = "(11,C) (5,) (7,AB)";
StringTokenizer st = new StringTokenizer(a, "(,)");
while(st.hasMoreTokens()) {
points.add(st.nextToken());
}
}
System.out.println(points);
List <Integer> digits = new ArrayList <Integer> ();
List <String> letters = new ArrayList <String> ();
Matcher m = Pattern.compile ("\\((\\d+),(\\w*)\\)").matcher (string);
while (m.find ())
{
digits.add (Integer.valueOf (m.group (1)));
letters.add (m.group (2));
}
Must be like this
String[] values = a.split("\\) \\(");
String[][] result = new String[values.length][2];
for (int i = 0; i < values.length; i++) {
values[i] = values[i].replaceAll("\\(|\\)", "") + " ";
result[i] = values[i].split("\\,");
System.out.println(result[i][0] + " * " + result[i][1]);
}
result will contain coordinate pairs.
public static void main(String[] args) {
String s = "(11,C), (5,) ,(7,AB)";
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> number = new ArrayList<Integer>();
int intIndex = 0, stringIndex = 0;
String[] arr = s.split(",");
for (int i = 0; i < arr.length; i++) {
String ss = arr[i].replace("(", "");
ss = ss.replace(")", "");
boolean b = isNumeric(ss);
// System.out.println( Arrays.toString(arr));
if (b) {
int num = Integer.valueOf(ss.trim()).intValue();
number.add(num);
} else
name.add(ss);
}
System.out.println(name);
System.out.println(number);
}
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
Try this: I have slightly changed the input from "(11,C) (5,) (7,AB)" to "(11,C), (5,) ,(7,AB)" .
Output:
[C, , AB]
[11, 5, 7]
Brutal coding, in raw level:
List<String> points = new ArrayList<String> ();
String source= "(11,C) (5,) (7,AB)";
StringTokenizer deleteLeft = new StringTokenizer(source, "(");
while(deleteLeft.hasMoreTokens()) {
StringTokenizer deleteRight = new StringTokenizer(deleteLeft.nextToken(), ")");
points.add(deleteRight.nextToken());
}
System.out.println(points);
}

Words inside square brackes - RegExp

String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = reg.exec(text);
for (int i = 0; i < matchResult.getGroupCount(); i++) {
System.out.println("group" + i + "=" + matchResult.getGroup(i));
}
I am trying to get all blocks which are encapsulated by squared bracets form a path string:
and I only get group0="[build]" what i want is:
1:"[build]" 2:"[something]" 3:"[build]"
EDIT:
just to be clear words inside the brackets are generated with random text
public static String genText()
{
final int LENGTH = (int)(Math.random()*12)+4;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random() * 26) + 97));
}
String str = sb.toString();
str = str.substring(0,1).toUpperCase() + str.substring(1);
return str;
}
EDIT 2:
JDK works fine, GWT RegExp gives this problem
SOLVED:
Answer from Didier L
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String result = "";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = null;
while((matchResult=reg.exec(text)) != null){
if(matchResult.getGroupCount()==1)
System.out.println( matchResult.getGroup(0));
}
I don't know which regex library you are using but using the one from the JDK it would go along the lines of
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
Pattern pat = Pattern.compile(linkPattern);
Matcher mat = pat.matcher(text);
while (mat.find()) {
System.out.println(mat.group());
}
Output:
[build]
[something]
[build]
Try:
String linkPattern = "(\\[[A-Za-z_0-9]+\\])*";
EDIT:
Second try:
String linkPattern = "\\[(\\w+)\\]+"
Third try, see http://rubular.com/r/eyAQ3Vg68N

array in array list

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

Categories

Resources