extract multiples same string from a string - java

I need to split a String by a specific String which can be placed anywhere (there can be multiple occurences of this string at same time) and reconstruct the entire string by adding extracts into something like a StringBuffer. The case of the specific String to seek must be insensitive
For example:
String targeted = "test" ;
String plainString ="azertytestqwerty";
//desired outcome
StringBuffer sb = new StringBuffer();
sb.append("azerty");
sb.append("test");
sb.append("qwerty");
--------------------------
String targeted = "test" ;
String plainString ="a.test";
//desired outcome
StringBuffer sb = new StringBuffer();
sb.append("a.");
sb.append("test");
--------------------------
String targeted = "test" ;
String plainString ="test mlm";
//desired outcome
StringBuffer sb = new StringBuffer();
sb.append("test");
sb.append("mlm");
--------------------------
String targeted = "test" ;
String plainString ="aaatestzzztest";
//desired outcome
StringBuffer sb = new StringBuffer();
sb.append("aaa");
sb.append("test");
sb.append("zzz");
sb.append("test");
Any simple way to do this?
I think I need to use a regex like:
Pattern pattern = Pattern.compile(".*"+targeted +".*");
Matcher matcher = pattern.matcher(text);
if (matcher.find())
{
System.out.println(matcher.group(1));
}
But then I don't know how to extract the strings and add them in same order
The reason why I do this it's because the plainString will be added into a Excel cell using POI but I need to add font color for the targeted string.
Example:
XSSFRichTextString richString = new XSSFRichTextString();
richString.append("azerty");
richString.append("test", highlightFont);
richString.append("qwerty");
cell.setCellValue(richString);
Thank you very much

Here is the method, you can try any combination.
public String extractMultiples(String plainString, String targeted) {
StringBuffer sb = new StringBuffer();
// split covers all occurrences in the beginning;empty element, and in
// the middle
String[] result = plainString.split(targeted);
for (int i = 0; i < result.length; i++) {
sb.append(result[i]);
if (i < result.length - 1)// not the last one
sb.append(targeted);
}
// in the end
if (plainString.endsWith(targeted))
sb.append(targeted);
return sb.toString();
}

Pattern and Matcher are maybe a little bit too much...
just do a split on the word and then make a for loop over the resulting array...
Example
public static void main(String[] args) {
String targeted = "test";
String plainString = "azertytestqwerty";
String[] result = plainString.split(targeted);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.length; i++) {
sb.append(result[i]);
}
}

Related

how to delete up extra line breakers in string

I have got a text like this in my String s (which I have already read from txt.file)
trump;Donald Trump;trump#yahoo.eu
obama;Barack Obama;obama#google.com
bush;George Bush;bush#inbox.com
clinton,Bill Clinton;clinton#mail.com
Then I'm trying to cut off everything besides an e-mail address and print out on console
String f1[] = null;
f1=s.split("(.*?);");
for (int i=0;i<f1.length;i++) {
System.out.print(f1[i]);
}
and I have output like this:
trump#yahoo.eu
obama#google.com
bush#inbox.com
clinton#mail.com
How can I avoid such output, I mean how can I get output text without line breakers?
Try using below approach. I have read your file with Scanner as well as BufferedReader and in both cases, I don't get any line break. file.txt is the file that contains text and the logic of splitting remains the same as you did
public class CC {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(new File("file.txt"));
while (scan.hasNext()) {
String f1[] = null;
f1 = scan.nextLine().split("(.*?);");
for (int i = 0; i < f1.length; i++) {
System.out.print(f1[i]);
}
}
scan.close();
BufferedReader br = new BufferedReader(new FileReader(new File("file.txt")));
String str = null;
while ((str = br.readLine()) != null) {
String f1[] = null;
f1 = str.split("(.*?);");
for (int i = 0; i < f1.length; i++) {
System.out.print(f1[i]);
}
}
br.close();
}
}
You may just replace all line breakers as shown in the below code:
String f1[] = null;
f1=s.split("(.*?);");
for (int i=0;i<f1.length;i++) {
System.out.print(f1[i].replaceAll("\r", "").replaceAll("\n", ""));
}
This will replace all of them with no space.
Instead of split, you might match an email like format by matching not a semicolon or a whitespace character one or more times using a negated character class [^\\s;]+ followed by an # and again matching not a semicolon or a whitespace character.
final String regex = "[^\\s;]+#[^\\s;]+";
final String string = "trump;Donald Trump;trump#yahoo.eu \n"
+ " obama;Barack Obama;obama#google.com \n"
+ " bush;George Bush;bush#inbox.com \n"
+ " clinton,Bill Clinton;clinton#mail.com";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
final List<String> matches = new ArrayList<String>();
while (matcher.find()) {
matches.add(matcher.group());
}
System.out.println(String.join("", matches));
[^\\s;]+#[^\\s;]+
Regex demo
Java demo
package com.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String s = "trump;Donald Trump;trump#yahoo.eu "
+ "obama;Barack Obama;obama#google.com "
+ "bush;George Bush;bush#inbox.com "
+ "clinton;Bill Clinton;clinton#mail.com";
String spaceStrings[] = s.split("[\\s,;]+");
String output="";
for(String word:spaceStrings){
if(validate(word)){
output+=word;
}
}
System.out.println(output);
}
public static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile(
"^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}$",
Pattern.CASE_INSENSITIVE);
public static boolean validate(String emailStr) {
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
return matcher.find();
}
}
Just replace '\n' that may arrive at start and end.
write this way.
String f1[] = null;
f1=s.split("(.*?);");
for (int i=0;i<f1.length;i++) {
f1[i] = f1[i].replace("\n");
System.out.print(f1[i]);
}

String reverse using Java'sstringbuilder

I develop using Java to make a little project.
I want String reverse.
If I entered "I am a girl", Printed reversing...
Already I tried to use StringBuilder.
Also I write it using StringBuffer grammar...
But I failed...
It is not printed my wish...
WISH
My with Print -> "I ma a lrig"
"I am a girl" -> "I ma a lrig" REVERSE!!
How can I do?..
Please help me thank you~!!!
public String reverse() {
String[] words = str.split("\\s");
StringTokenizer stringTokenizer = new StringTokenizer(str, " ");
for (String string : words) {
System.out.print(string);
}
String a = Arrays.toString(words);
StringBuilder builder = new StringBuilder(a);
System.out.println(words[0]);
for (String st : words){
System.out.print(st);
}
return "";
}
Java 8 code to do this :
public static void main(String[] args) {
String str = "I am a girl";
StringBuilder sb = new StringBuilder();
// split() returns an array of Strings, for each string, append it to a StringBuilder by adding a space.
Arrays.asList(str.split("\\s+")).stream().forEach(s -> {
sb.append(new StringBuilder(s).reverse() + " ");
});
String reversed = sb.toString().trim(); // remove trailing space
System.out.println(reversed);
}
O/P :
I ma a lrig
if you do not want to go with lambda then you can try this solution too
String str = "I am a girl";
String finalString = "";
String s[] = str.split(" ");
for (String st : s) {
finalString += new StringBuilder(st).reverse().append(" ").toString();
}
System.out.println(finalString.trim());
}

Java - Add numbers to matching words

I'm trying to add a count number for matching words, like this:
Match word: "Text"
Input: Text Text Text TextText ExampleText
Output: Text1 Text2 Text3 Text4Text5 ExampleText6
I have tried this:
String text = "Text Text Text TextText ExampleText";
String match = "Text";
int i = 0;
while(text.indexOf(match)!=-1) {
text = text.replaceFirst(match, match + i++);
}
Doesn't work because it would loop forever, the match stays in the string and IndexOf will never stop.
What would you suggest me to do?
Is there a better way doing this?
Here is one with a StringBuilder but no need to split:
public static String replaceWithNumbers( String text, String match ) {
int matchLength = match.length();
StringBuilder sb = new StringBuilder( text );
int index = 0;
int i = 1;
while ( ( index = sb.indexOf( match, index )) != -1 ) {
String iStr = String.valueOf(i++);
sb.insert( index + matchLength, iStr );
// Continue searching from the end of the inserted text
index += matchLength + iStr.length();
}
return sb.toString();
}
first take one stringbuffer i.e. result,Then spilt the source with the match(destination).
It results in an array of blanks and remaining words except "Text".
then check condition for isempty and depending on that replace the array position.
String text = "Text Text Text TextText ExampleText";
String match = "Text";
StringBuffer result = new StringBuffer();
String[] split = text.split(match);
for(int i=0;i<split.length;){
if(split[i].isEmpty())
result.append(match+ ++i);
else
result.append(split[i]+match+ ++i);
}
System.out.println("Result is =>"+result);
O/P
Result is => Text1 Text2 Text3 Text4Text5 ExampleText6
Try this solution is tested
String text = "Text Text Text TextText Example";
String match = "Text";
String lastWord=text.substring(text.length() -match.length());
boolean lastChar=(lastWord.equals(match));
String[] splitter=text.split(match);
StringBuilder sb = new StringBuilder();
for(int i=0;i<splitter.length;i++)
{
if(i!=splitter.length-1)
splitter[i]=splitter[i]+match+Integer.toString(i);
else
splitter[i]=(lastChar)?splitter[i]+match+Integer.toString(i):splitter[i];
sb.append(splitter[i]);
if (i != splitter.length - 1) {
sb.append("");
}
}
String joined = sb.toString();
System.out.print(joined+"\n");
One possible solution could be
String text = "Text Text Text TextText ExampleText";
String match = "Text";
StringBuilder sb = new StringBuilder(text);
int occurence = 1;
int offset = 0;
while ((offset = sb.indexOf(match, offset)) != -1) {
// fixed this after comment from #RealSkeptic
String insertOccurence = Integer.toString(occurence);
sb.insert(offset + match.length(), insertOccurence);
offset += match.length() + insertOccurence.length();
occurence++;
}
System.out.println("result: " + sb.toString());
This will work for you :
public static void main(String[] args) {
String s = "Text Text Text TextText ExampleText";
int count=0;
while(s.contains("Text")){
s=s.replaceFirst("Text", "*"+ ++count); // replace each occurrence of "Text" with some place holder which is not in your main String.
}
s=s.replace("*","Text");
System.out.println(s);
}
O/P:
Text1 Text2 Text3 Text4Text5 ExampleText6
I refactored #DeveloperH 's code to this:
public class Snippet {
public static void main(String[] args) {
String matchWord = "Text";
String input = "Text Text Text TextText ExampleText";
String output = addNumbersToMatchingWords(matchWord, input);
System.out.print(output);
}
private static String addNumbersToMatchingWords(String matchWord, String input) {
String[] inputsParts = input.split(matchWord);
StringBuilder outputBuilder = new StringBuilder();
int i = 0;
for (String inputPart : inputsParts) {
outputBuilder.append(inputPart);
outputBuilder.append(matchWord);
outputBuilder.append(i);
if (i != inputsParts.length - 1)
outputBuilder.append(" ");
i++;
}
return outputBuilder.toString();
}
}
We can solve this by using stringbuilder, it provides simplest construct to insert character in a string. Following is the code
String text = "Text Text Text TextText ExampleText";
String match = "Text";
StringBuilder sb = new StringBuilder(text);
int beginIndex = 0, i =0;
int matchLength = match.length();
while((beginIndex = sb.indexOf(match, beginIndex))!=-1) {
i++;
sb.insert(beginIndex+matchLength, i);
beginIndex++;
}
System.out.println(sb.toString());

How to replace space with hyphen?

I want to replace Space with "-" what is the way
Suppose my code is
StringBuffer tokenstr=new StringBuffer();
tokenstr.append("technician education systems of the Cabinet has approved the following");
I want output
"technician-education-systems-of-the-Cabinet-has-approved-the-following"
thanks
Like this,
StringBuffer tokenstr = new StringBuffer();
tokenstr.append("technician education systems of the Cabinet has approved the following");
System.out.println(tokenstr.toString().replaceAll(" ", "-"));
and like this as well
System.out.println(tokenstr.toString().replaceAll("\\s+", "-"));
Do like this
StringBuffer tokenstr=new StringBuffer();
tokenstr.append("technician education systems of the Cabinet has approved the following".replace(" ", "-"));
System.out.print(tokenstr);
You may try this :
//First store your value in string object and replace space with "-" before appending it to StringBuffer.
String str = "technician education systems of the Cabinet has approved the following";
str = str.replaceAll(" ", "-");
StringBuffer tokenstr=new StringBuffer();
tokenstr.append(str);
System.out.println(tokenstr);
you need to write custom replaceAll method. Where you need to find out src string index and replace those string sub-string with destination string.
Please find a code snippet by Jon Skeet
If you dont want to jump back and forth between StringBuffer and String classes, you can do this:
StringBuffer tokenstr = new StringBuffer();
tokenstr.append("technician education systems of the Cabinet has approved the following");
int idx=0;
while( idx = tokenstr.indexOf(" ", idx) >= 0 ) {
tokenstr.replace(idx,idx+1,"-");
}
If you have the StringBuffer object then you need to iterate it and replace the character:
for (int index = 0; index < tokenstr.length(); index++) {
if (tokenstr.charAt(index) == ' ') {
tokenstr.setCharAt(index, '-');
}
}
or convert it into String then replace as below :
String value = tokenstr.toString().replaceAll(" ", "-");
/You can use below method pass your String parameter and get result as String spaces replaced with hyphen /
private static String replaceSpaceWithHypn(String str) {
if (str != null && str.trim().length() > 0) {
str = str.toLowerCase();
String patternStr = "\\s+";
String replaceStr = "-";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(str);
str = matcher.replaceAll(replaceStr);
patternStr = "\\s";
replaceStr = "-";
pattern = Pattern.compile(patternStr);
matcher = pattern.matcher(str);
str = matcher.replaceAll(replaceStr);
}
return str;
}

convert List<String> to a static string if possible

I am trying to wrap my head around List<String> I have a dynamicly created array List<String> selected_tags That I would like to convert to break apart the elements and place a "%" inbetween each element so I can use the new string in a http call.
Creat my new List :
public List<String> selected_tags = new ArrayList<String>();
Fill my List string
for (int i = 0; i < tags.length; i++) {
if (selected[i] == true){
selected_tags.add(tags[i]);
}
}
I then need to use selected_tags in my url
HttpGet httpPost = new HttpGet("http://www.mywebsite.com/scripts/getData.php?tags="+ BROKEN DOWN LIST<STRING>);
I would like for it to look like
HttpGet httpPost = new HttpGet("http://www.mywebsite.com/scripts/getData.php?tags=tag1%tag2%tag3);
StringBuilder s = new StringBuilder();
boolean first = true;
for (String tag : selected_tags) {
if (!first)
s.append("%");
else
first = false;
s.append(tag);
}
String myUrlString = "tags=" + s.toString();
actually, you should have something like
StringBuilder sb = new StringBuilder();
if(selected_tags.size() > 0) {
sb.append(selected_tags.get(0);
for(int i = 1 ; i < selected_tags.size(); i++) {
sb.append("%");
sb.append(selected_tags.get(i));
}
}
return sb.toString();
StringBuilder result = new StringBuilder();
String prepend = "tags=";
for( String tag : selected_tags ){
result.append(prepend).append(tag);
prepend = "%";
}
String resultString = result.toString();
StringBuilder sb = new StringBuilder();
for (String tag : selected_tags) {
sb.append("%").append(tag);
}
sb.replace(0,1,"tags=");

Categories