Storing in String [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the most elegant way to concatenate a list of values with delimiter in Java?
I have 3 different words listed in property file in 3 different lines.
QWERT
POLICE
MATTER
I want to read that property file and store those 3 words in String, not in aarylist separated by whitespace. The output should look like this
String str = { QWERT POLICE MATTER}
Now I used the follwoing code and getting the output without white space in between the words:
String str = {QWERTPOLICEMATTER}. What should I do to the code to get the string result with words separated by whitespace.
FileInputStream in = new FileInputStream("abc.properties");
pro.load(in);
Enumeration em = pro.keys();
StringBuffer stringBuffer = new StringBuffer();
while (em.hasMoreElements()){
String str = (String)em.nextElement();
search = (stringBuffer.append(pro.get(str)).toString());

Try:
search = (stringBuffer.append(" ").append(pro.get(str)).toString());

Just append a blank space in your loop. See the extra append below:
while (em.hasMoreElements()){
String str = (String)em.nextElement();
search = (stringBuffer.append(pro.get(str)).toString());
if(em.hasNext()){
stringBuffer.append(" ")
}
}

Related

Deleting exact match String from text file [duplicate]

This question already has answers here:
Find a line in a file and remove it
(17 answers)
Closed 1 year ago.
I am trying to remove a specific string in my text file. Current code gets the line one by one until 50 is hit. I am trying to remove the string (EXACT MATCH!) in the notepad, but not sure how to do so.
Scanner input = new Scanner(new File("C:\\file.txt"));
int counter = 0;
while(input.hasNextLine() && counter < 50) {
counter++;
String tempName = input.nextLine();
//perform my custom code here
//somehow delete tempName from the text file (exact match)
}
I have tried input.nextLine().replaceFirst(tempName, ""); without any luck
If you are using Java 8, You can do something like below using java.nio package:
Path p = Paths.get("PATH-TO-FILE");
List<String> lines = Files.lines(p)
.map(str -> str.replaceFirst("STRING-TO-DELETE",""))
.filter(str -> !str.equals(""))
.collect(Collectors.toList());
Files.write(p, lines, StandardCharsets.UTF_8);
Below line replaces "the" with "**"
Pattern pattern = Pattern.compile("the", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(tempName);
String repalcedvalue = matcher.replaceAll("**");

How To Parse String In Java With * [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 2 years ago.
I have a string like this.
PER*IP**TE**1234567890*EM*sampleEmail#Email.com
How can I parse the string into multiple lines like this in Java?
PER
IP
TE
//Empty String
EM
1234567890
sampleEmail#Email.com
You could use a regex replacement:
String input = "PER*IP**TE*1234567890*EM*sampleEmail#Email.com";
String output = input.replaceAll("\\*", "\n");
System.out.println(output);
This prints:
PER
IP
TE
1234567890
EM
sampleEmail#Email.com
You can use String#split. Since * is a regular expression metacharacter, you need to escape it with a backslash or use Pattern#quote.
Arrays.stream("PER*IP**TE**1234567890*EM*sampleEmail#Email.com".split(Pattern.quote("*")))
.forEach(System.out::println);
String newstring = string.replace("*", "\n");
System.out.println(newstring);
now if you don't want that the empty line show up, use this:
String string = "PER*IP**TE**1234567890*EM*sampleEmail#Email.com"
String newstring = string.replaceAll("\\*+","*").replace("*", "\n");
System.out.println(newstring);

Replacing multiple substrings from a string in Java/Android [duplicate]

This question already has answers here:
Java Replacing multiple different substring in a string at once (or in the most efficient way)
(11 answers)
Closed 6 years ago.
Example:
String originalString = "This is just a string folks";
I want to remove(or replace them with "") : 1. "This is" , 2. "folks"
Desired output :
finalString = "just a string";
For a sole substring it's easy, we can just use replace/replaceAll.
I also know it works for various numeric values replace("[0-9]","")
But can that be done for characters?
You can create a function like below:
String replaceMultiple (String baseString, String ... replaceParts) {
for (String s : replaceParts) {
baseString = baseString.replaceAll(s, "");
}
return baseString;
}
And call it like:
String finalString = replaceMultiple("This is just a string folks", "This is", "folks");
You can pass multiple strings that are to be replaced after the first parameter.
It works like this:
String originalString = "This is just a string folks";
originalString = originalString.replace("This is", "");
originalString = originalString.replace("folks", "");
//originalString is now finalString

Splitting of String delimited by '[' and ']' [duplicate]

This question already has answers here:
java regular expression to extract content within square brackets
(3 answers)
How do I split a string in Java?
(39 answers)
Closed 8 years ago.
I have some sampel data written on a file. The data are in the following format -
[Peter Jackson] [UK] [United Kingdom] [London]....
I have to extract the information delimited by '[' and ']'. So that I found -
Peter Jackson
UK
United Kingdom
London
...
...
I am not so well known with string splitting. I only know how to split string when they are only separated by a single character (eg - string1-string2-string3-....).
You should use regex for this.
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher results = p.matcher("[Peter Jackson] [UK] [United Kingdom] [London]....");
while (results.find()) {
System.out.println(results.group(1));
}
You can use this regex:
\\[(.+?)\\]
And the captured group will have your content.
Sorry for not adding the code. I don't know java
Is each item separated by spaces? if so, you could split by "\] \[" then replace all the left over brackets:
String vals = "[Peter Jackson] [UK] [United Kingdom] [London]";
String[] list = vals.split("\\] \\[");
for(String str : list){
str = str.replaceAll("\\[", "").replaceAll("\\]", "");
System.out.println(str);
}
Or if you want to avoid a loop you could use a substring to remove the beginning and ending brackets then just separate by "\\] \\[" :
String vals = " [Peter Jackson] [UK] [United Kingdom] [London] ";
vals = vals.trim(); //removes beginning whitspace
vals = vals.substring(1,vals.length()-1); // removes beginning and ending bracket
String[] list = vals.split("\\] \\[");
Try to replace
String str = "[Peter Jackson] [UK] [United Kingdom] [London]";
str = str.replace("[", "");
str = str.replace("]", "");
And then you can try to split it.
Splitting on "] [" should sort you, as in:
\] \[
Debuggex Demo
After this, just replace the '[' and the ']' and join using newline.

Splitting Java string with quotation marks [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can you recommend a Java library for reading (and possibly writing) CSV files?
I need to split the String in Java. The separator is the space character.
String may include the paired quotation marks (with some text and spaces inside) - the whole body inside the paired quotation marks should be considered as the single token.
Example:
Input:
token1 "token 2" token3
Output: array of 3 elements:
token1
token 2
token3
How to do it?
Thanks!
Split twice. First on quotes, then on spaces.
Assuming that the other solutions will not work for you, because they do not properly detect matching quotes or ignore spaces within quoted text, try something like:
private void addTokens(String tokenString, List<String> result) {
String[] tokens = tokenString.split("[\\r\\n\\t ]+");
for (String token : tokens) {
result.add(token);
}
}
List<String> result = new ArrayList<String>();
while (input.contains("\"")) {
String prefixTokens = input.substring(0, input.indexOf("\""));
input = input.substring(input.indexOf("\"") + 1);
String literalToken = input.substring(0, input.indexOf("\""));
input.substring(input.indexOf("\"") + 1);
addTokens(prefixTokens, result);
result.add(literalToken);
}
addTokens(input, result);
Note that this won't handle unbalanced quotes, escaped quotes, or other cases of erroneous/malformed input.
import java.util.StringTokenizer;
class STDemo {
static String in = "token1;token2;token3"
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, ";");
while(st.hasMoreTokens()) {
String val = st.nextToken();
System.out.println(val);
}
}
}
this is easy way to string tokenize

Categories

Resources