This is a small snippet of my code.It works fine but what if I wanted to add a number to each String variable str.
How do I do that?Please help.
Collections.shuffle(arrlist);
for(int i=0;i<nb;i++){
String str = (String) arrlist.get(i);
//worker.parseXHtml(writer, document, new StringReader("<br>"));
worker.parseXHtml(writer, document, new StringReader(str));
}
Try
String str = (String) arrlist.get(i)+String.valueOf(someNumber);
If you want to add i
String str = (String) arrlist.get(i)+String.valueOf(i);
Update
public static void main(String[] args) {
List arrlist = new ArrayList<>();
arrlist.add("tester");
int i = 0;
String str = (String) arrlist.get(i) + String.valueOf(i);
System.out.println(str);
}
o/p:
tester0
Related
I am going through a project where I need to remove all java keywords from a java file. First I create a keyword.java file and store all java keywords into this file.Like abstract continue for new switch assert default goto package etc which I store keyword.java file. I have another file named newFile.java and I read all data from newFile.java as a String. I have to remove all java keywords from newFile.java file. As far I tried:
public void processFile() throws IOException {
String data = "";
data = new String(Files.readAllBytes(Paths.get("H:\\java\\Clone\\newFile.java"))).trim();
String rmvPunctuation = removePunctuation(data);
String newLineRemove = rmvPunctuation.replace("\n", "").replace("\r", "");
String spaceRemove = newLineRemove.replaceAll("( ){2,}", " ");
removeKeyword(spaceRemove);}
public void removeKeyword(String fileAsString) throws FileNotFoundException, IOException {
ArrayList<String> keyWordList = new ArrayList<>();
ArrayList<String> methodContentList = new ArrayList<>();
FileInputStream fis = new FileInputStream("H:\\java\\keyword.java");
byte[] b = new byte[fis.available()];
fis.read(b);
String[] keyword = new String(b).trim().split(" ");
String newString = "";
for (int i = 0; i < keyword.length; i++) {
keyWordList.add(keyword[i].trim());
}
String[] p = fileAsString.split(" ");
for (int i = 0; i < p.length; i++) {
if (!(keyWordList.contains(p[i].trim()))) {
newString = newString + p[i] + " ";
}
}
System.out.println("" + newString);
}
But I could not found my desired output. All the java keywords are not removed from newFile.java file. I think StackOverflow community help me to solve this. I am also a beginner.
I also tried:
public void removeKeyword(String fileAsString) throws IOException {
String keyWord = new String(Files.readAllBytes(Paths.get("H:\\java\\keyword.java"))).trim();
String text = fileAsString.trim();
ArrayList<String> wordList = new ArrayList<>();
ArrayList<String> keyWordList = new ArrayList<>();
wordList.addAll(Arrays.asList(text.split(" ")));
keyWordList.addAll(Arrays.asList(keyWord.split(" ")));
wordList.removeAll(keyWordList);
System.out.println("" + wordList.toString());
}
I want to convert an ArrayList of Integers to a single string.
For example:
List<Integers> listInt= new ArrayList();
String str = "";
listInt.add(1);
listInt.add(2);
listInt.add(3);
// I want the output to be: str = "123";
String numberString = listInt.stream().map(String::valueOf)
.collect(Collectors.joining(""));
//You can pass a delimiter if you want to the joining() function, like a comma. ","
Try this, the simplest way:
List<Integer> listInt = Arrays.asList(1,2,3);
String str = "";
StringBuilder builder = new StringBuilder();
for(Integer item : listInt)
builder.append(item);
str = builder.toString();
System.out.println(str);
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'm having a Json file like this {"Name":"Saaa","AppIcon":"ddd.jpg","Wallpaper.jpg","ddd.jpg"]}. I need to extract the AppIcon values.I'm using json simple lib to parse the json.The code snippet to parse the values is as below.
FileReader appIconReader = new FileReader("jsonpath.json");
JSONObject jsonIconObject = (JSONObject)jsonParser.parse(appIconReader);
System.out.println("APPLICATION ICON = "+jsonIconObject.get("AppIcon"));
But the output what I'm gettin is a single string as below:
["ddd.jpg","Wallpaper.jpg","ddd.jpg"]
I need to extract the individual values like this
ddd.jpg
Wallpaper.jpg
ddd.jpg
Not with the square brackets([]) and double quotes("") as I'm getting right now.How can I do that?
Try with JSON.
String str="[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
Type collectionType = new TypeToken<String[]>() {
}.getType();
String[] a=new Gson().fromJson(str,collectionType);
for (String i:a){
System.out.println(i);
}
Output
ddd.jpg
Wallpaper.jpg
ddd.jpg
Edit: for your edited question answer like this.
public class Obj{
private String name;
private List<String> appIcons;
public List<String> getAppIcons() {
return appIcons;
}
public void setAppIcons(List<String> appIcons) {
this.appIcons = appIcons;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now you can simply pass your JSON
String str = "{\"name\":\"Saaa\",\"appIcons\":
[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]}";
Obj obj = new Gson().fromJson(str, Obj.class);
System.out.println(obj.getAppIcons());
Output:
[ddd.jpg, Wallpaper.jpg, ddd.jpg]
Assuming you have your source string:
String str = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
Substring it:
str = str.substring(1, str.length() - 1);
Split it:
String[] parts = str.split(",");
Substring each part:
for(int i = 0; i < parts.length; i++) {
parts[i] = parts[i].substring(1, parts[i].length() - 1);
}
Now you have an array with each value. Note that this is unsafe, add checks before substringing.
this is what you want :
String filePath = "pathofjson\\test.json";
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray lang= (JSONArray) jsonObject.get("AppIcon");
System.out.println(lang);
for(int i=0; i<lang.size(); i++){
System.out.println(lang.get(i));
}
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
You can use replaceAll and split
String s="[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
String array[]=s.replaceAll("[\\[\\]\"]", "").split(","));
System.out.println(Arrays.toString(array);
replaceAll removes [ ] and " from String
split gives array of String by splitting the String with use of ,(delimeter)
Arrays.toString used to print Array.
OUTPUT
[ddd.jpg, Wallpaper.jpg, ddd.jpg]
With JSON you can try this
String s="{\"Name\":\"Saaa\","+
" \"AppIcon\":[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]}";
org.json.JSONObject json=new org.json.JSONObject(s);
org.json.JSONArray jarray=json.getJSONArray("AppIcon");
System.out.println(jarray.get(0));//Will give ddd.jpg
//Iterate over array to get all
Try this :
String str = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
String tempStr = str.replaceAll("\\W{2,}", ",");
String substring = tempStr.substring(1, tempStr.length() -1);
String[] strArray = substring.split(",");
You should use java.util.StringTokenizer
String s = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
StringTokenizer tokenizer = new StringTokenizer(s, "[\",]");
while (tokenizer.hasMoreElements()) {
System.out.println(tokenizer.nextElement());
}
Here you have a possible solution:
String data = "{\"Name\":\"Saaa\",\"AppIcon\":[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]}";
data = data.replaceAll("(.*\"AppIcon\":\\[)(.+)(\\].*)", "$2");
data = data.replaceAll("\"", "");
for(String str: data.split(",")) {
System.out.println(str);
}
which only involves the String class explicitly, and works for every String which the format defined in the question (which has "AppIcon:[]").
Following the description this is what you asked for:
String s = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"," +
"\"Wallpaper.jpg\",\"ddd.jpg\"," +
"\"Wallpaper.jpg\",\"ddd.jpg\"]";
String [] almost_the_words = s.split("\",\"");
int l = almost_the_words.length;
ArrayList<String> words = new ArrayList<String>();
String temp1 = almost_the_words[0].split("\"")[1];
String temp2 = almost_the_words[l-1].split("\"")[0];
words.add(temp1);
for(int i=1; i< l-1; i++) {
words.add(almost_the_words[i]);
}
words.add(temp2);
for(String w : words) {
System.out.println(w);
}
EDIT:
Parse a JSON File with those Strings using GSON:
import java.util.ArrayList;
public class MyObject {
ArrayList<String> appicon;
public MyObject(ArrayList<String> appicon) {
super();
this.appicon = appicon;
}
public ArrayList<String> getAppicon() {
return appicon;
}
public void setAppicon(ArrayList<String> appicon) {
this.appicon = appicon;
}
}
Use the class "MyObject" with the Library GSON: https://code.google.com/p/google-gson/
public class TagHandler {
private final String START = "<START ";
private final String END = "<END ";
public String handleTag(String buf, String[] attrList) {
String startPattern1 = START+attrList[0]+">";
String endPattern1 = END+attrList[0]+">";
String startPattern2 = START+attrList[1]+">";
String endPattern2 = END+attrList[1]+">";
String startPattern3 = START+attrList[2]+">";
String endPattern3 = END+attrList[2]+">";
String startPattern4 = START+attrList[3]+">";
String endPattern4 = END+attrList[3]+">";
String startPattern5 = START+attrList[4]+">";
String endPattern5 = END+attrList[4]+">";
String extract1 = new String(buf);
String extract2 = new String(buf);
String extract3 = new String(buf);
String extract4 = new String(buf);
String extract5 = new String(buf);
extract1 = extract1.substring(extract1.indexOf(startPattern1)+startPattern1.length(), extract1.indexOf(endPattern1));
extract2 = extract2.substring(extract2.indexOf(startPattern2)+startPattern2.length(), extract2.indexOf(endPattern2));
extract3 = extract3.substring(extract3.indexOf(startPattern3)+startPattern3.length(), extract3.indexOf(endPattern3));
extract4 = extract4.substring(extract4.indexOf(startPattern4)+startPattern4.length(), extract4.indexOf(endPattern4));
extract5 = extract5.substring(extract5.indexOf(startPattern5)+startPattern5.length(), extract5.indexOf(endPattern5));
String s = ("BLOPABP"+extract1) + ("\nBLOPCALL"+extract2) +("\nBLOPEXP"+extract3) +("\nBLOPHEAD"+extract4)+("\nBLOPMAJ"+extract5);
return s;
}
How would I tidy up the code above into some sort of loop? Basically I have a file that i'm reading and extract the data within the tags and I'm passing the tags into this TagHandler method and returning the extracted data as a string with the tag headers without the "< START >" and "< END TAG"> leaving only the header on the start tag.
Here you go. This should do what you want.
public class TagHandler {
private final String START = "<START ";
private final String END = "<END ";
public String handleTag(String buf, String[] attrList) {
String[] blop = {"BLOPABP", "BLOPCALL", "BLOPEXP", "BLOPHEAD", "BLOPMAJ"};
String s = "";
for (int i = 0; i < attrList.length; i++) {
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = buf.substring(buf.indexOf(startPattern)+startPattern.length(), buf.indexOf(endPattern));
s += blop[i]+extract;
if (i < attrList.length-1) {
s += "\n";
}
}
return s;
}
}
Look out for an out of bounds exception, if attrList has more than 5 elements.
You can try something like this, optimize it if you can :
public String handleTag(String buf, String[] attrList) {
StringBuilder temp = new StringBuilder();
final String[] prefix = {"BLOPABP","\nBLOPCALL","\nBLOPEXP",
"\nBLOPHEAD","\nBLOPMAJ"};
for(int i=0;i<attrList.length;i++){
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = new String(buf);
extract = extract.substring(
extract.indexOf(startPattern)+startPattern.length(),
extract.indexOf(endPattern));
temp.append(prefix[i%5]+extract);
}
return temp.toString();
}
This should work. You can replace = new ArrayList<String> with = new ArrayList<>() if you're using java 7.
private final String START = "<START ";
private final String END = "<END ";
List<String> startPatterns = new ArrayList<String>();//can use ArrayList<> instead if java 1.7
List<String> stringExtracts = new ArrayList<String>();
final String[] tags = new String[]{"BLOPABP","\nBLOPCALL","\nBLOPEXP","\nBLOPHEAD","\nBLOPMAJ"};
public String handleTag(String buf, String[] attrList) {
int numPatterns = tags.length;
String s;
String extract = new String(buf);
for(int i=0; i<numPatterns; i++){
String startPattern = START+attrList[i]+">";
startPatterns.add(startPattern);
String endPattern = END+attrList[i]+">";
endPatterns.add(endPattern);
String extract = extract.substring(extract.indexOf(startPattern)+startPattern.length(), extract.indexOf(endPattern));
stringExtracts.add(extract);
s += tags[i] + extract;
}
return s;
}
This assumes that you need access to the individual startPatterns, endPatterns and stringExtracts again, not just s. If you only need s though then discard the ArrayLists - it will work like this:
private final String START = "<START ";
private final String END = "<END ";
final String[] tags = new String[]{"BLOPABP","\nBLOPCALL","\nBLOPEXP","\nBLOPHEAD","\nBLOPMAJ"};
public String handleTag(String buf, String[] attrList) {
int numPatterns = tags.length;
String s;
String extract = new String(buf);
for(int i=0; i<numPatterns; i++){
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = extract.substring(extract.indexOf(startPattern)+startPattern.length(), extract.indexOf(endPattern));
s += tags[i] + extract;
}
return s;
}