How to replace space with hyphen? - java

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

Related

How can i split String in java with custom pattern

I am trying to get the location data from this string using String.split("[,\\:]");
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
String[] str = location.split("[,\\:]");
How can i get the data like this.
str[0] = 27.980194
str[1] = 46.090199
str[2] = 0.48
str[3] = 1
str[4] = 6
Thank you for any help!
If you just want to keep the numbers (including dot separator), you can use:
String[] str = location.split("[^\\d\\.]+");
You will need to ignore the first element in the array which is an empty string.
That will only work if the data names don't contain numbers or dots.
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
Matcher m = Pattern.compile( "\\d+\\.*\\d*" ).matcher(location);
List<String> allMatches = new ArrayList<>();
while (m.find( )) {
allMatches.add(m.group());
}
System.out.println(allMatches);
Quick and Dirty:
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
List<String> strList = (List) Arrays.asList( location.split("[,\\:]"));
String[] str = new String[5];
int count=0;
for(String s : strList){
try {
Double d =Double.parseDouble(s);
str[count] = d.toString();
System.out.println("In String Array:"+str[count]);
count++;
} catch (NumberFormatException e) {
System.out.println("s:"+s);
}
}

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

extract multiples same string from a string

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

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

Java Regex And XML

I've been working on a weekend project, a simple, lightweight XML parser, just for fun, to learn more about Regexes. I've been able to get data in atributes and elements, but am having a hard time separating tags. This is what I have:
CharSequence inputStr = "<a>test</a>abc<b1>test2</b1>abc1";
String patternStr = openTag+"(.*?)"+closeTag;
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
StringBuffer buf = new StringBuffer();
boolean found = false;
while ((found = matcher.find())) {
String replaceStr = matcher.group();
matcher.appendReplacement(buf, "found tag (" + replaceStr + ")");
}
matcher.appendTail(buf);
String result = buf.toString();
System.out.println(result);
Output: found tag (<a>test</a>abc<b1>test2</b1>)abc1
I need to to end the 'found tag' at each tag, not the whole group. Any way I can have it do that? Thanks.
You can try with something as follows to get it working as you require;
int count = matcher.groupCount();
for(int i=0;i<count;i++)
{
String replaceStr = matcher.group(i);
matcher.appendReplacement(buf, "found tag (" + replaceStr + ")");
}

Categories