Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a String with some text, f.e.
"Thisisalongwordtest and I want tocutthelongword in pieces"
Now I want to cut the to longs word in 2 pieces with a blank. The word should be cut if it's longer than 10 characters.
The result should be:
"Thisisalon gwordtest and I want tocutthelo ngword in pieces"
How can I achieve this efficiently?
are you looking for this? or I misunderstood the question?
String newString = oldStr.replaceAll("\\w{10}","$0 "))
with your example, the newString is:
Thisisalon gwordtest and I want tocutthelo ngword in pieces
Edit for Pshemo's good comment
to avoid to add space after words with exact 10 chars:
str.replaceAll("\\w{10}(?=\\w)","$0 "));
.replaceAll("(\\w{10})(?=\\w)", "$1 ")
Tested with:
test("abcde fghij klmno pqrst");
test("abcdefghijklmnopqrst");
test("abcdefghijklmnopqrstuv");
test("abcdefghij klmnopqrstuv");
test("abcdefghij klmnopqrst uv");
separate text into words. (by space)
cut long words and replace source word with new words
assemble text again
Note, that this approach will kill multiple-spaces.
(?=\w{10,}\s)(\w{10})
Should be replaced by
"\1 "
you can use replace function.
If it has number or special characters
(?=\S{10,}\s)(\S{10})
can be used.
This is the code i wrote check it once.....
public class TakingInput {
public static void main(String[] args) {
String s="Thisisalongwordtest and I want tocutthelongword in pieces";
StringBuffer sb;
String arr[]=s.split(" ");
for(int i=0;i<arr.length;i++){
if(arr[i].length()>10){
sb=new StringBuffer(arr[i]);
sb.insert(10," ");
arr[i]=new String(sb);
}
}
for(String ss: arr){
System.out.println(ss);//o/p: "Thisisalon gwordtest and I want tocutthelo ngword in pieces"
}
}
}
This code will do exactly what you want.
First create a method that splits a String if its longer than 10 chars:
String splitIfLong(String s){
if(s.length() < 11) return s + " ";
else{
String result = "";
String temp = "";
for(int i = 0; i < s.length(); i++){
temp += s.charAt(i);
if(i == 9)
temp += " ";
result += temp;
temp = "";
}
return result + " ";
}
}
Then use Scanner to read every word in the sentence seperated by a white space" ":
String s = "Thisisalongwordtest and I want tocutthelongword in pieces";
String afterSplit = "";
Scanner in = new Scanner(s);
Then call the splitIfLong() method for every word in the sentence. And add what the method returns to a new String:
while(in.hasNext())
afterSplit += splitIfLong(in.next());
Now you can use the new String as you wish. If you call:
System.out.println(afterSplit);
it will print:
Thisisalon gwordtest and I want tocutthelo ngword in pieces
Hope this helps
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am not sure how to approach this problem. I've seen people using arrays but after trying it, it only worked for the whole string and not each words individually.
Thanks for the help!
You can use the split method to split the string into multiple words, saved in a String array. Then, get the first and last letter using the charAt method, and then concatenate them in the correct order to get the modified word.
String a = "This is a string with multiple words";
String[] arr = a.split(" "); //splits string into an array of strings, by separating with spaces
for (int i = 0; i < arr.length; i++) //looping through each word
{
if (arr[i].length() == 1) //don't change word if it only has 1 letter
{
System.out.print(arr[i] + " ");
continue;
}
//using charAt to obtain first and last letter of each word
char firstLetter = arr[i].charAt(0);
char lastLetter = arr[i].charAt(arr[i].length()-1);
String middle = arr[i].substring(1, arr[i].length()-1); //all letters of word except first and last
arr[i] = lastLetter + middle + firstLetter; //concatenating together to create new word
System.out.print(arr[i] + " "); //printing each word after switching letters
}
You seem like a beginner to Java, so I highly recommend you read the Java documentation on the String class and its methods, as Java has some pretty thorough and relatively easy to understand documentation.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
For example I have this string, where email addresses are differently formatted:
"a.b#c.d" <a.b#c.d>|"Michal pichal (michal.pichal#g.d)" <michal.pichal#g.d>|Melisko Pan <melisko.pan#domena.sk>
I need to extract the email addresses in a form of:
a.b#c.d|michal.pichal#g.d|melisko.pan#domena.sk
My idea was to get any char near # from group [0-9][A-Z][a-z]#.- but I do not know how. Please help with some hint.
This regex extracts emails out of your string:
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[\\w.]+#[\\w.]+");
Matcher matcher = pattern.matcher("\"a.b#c.d\" <a.b#c.d>|\"Michal pichal (michal.pichal#g.d)\" <michal.pichal#g.d>|Melisko Pan <melisko.pan#domena.sk>\r\n");
while(matcher.find()){
String group = matcher.group();
System.out.println("group="+group);
}
It prints:
group=a.b#c.d
group=a.b#c.d
group=michal.pichal#g.d
group=michal.pichal#g.d
group=melisko.pan#domena.sk
import java.util.Scanner;
class test{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String res = ""; //This holds the final result
for(int i=0; i<str.length(); ++i){ //Loop through the entire string
if(str.charAt(i)=='<'){
String build = "";
for(int j=i+1; j<str.length(); ++j){
if(str.charAt(j)=='>'){
break; //Break when we hit the '>'
}
build += str.charAt(j); //Add those between < and >
}
res += build + "|"; //Add the pipe at the end
}
continue;
}
System.out.println(res);
}
}
This ought to do it.
Just run simple nested loops. No need for regex.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Write a method called multiConcat that takes a String and an integer as parameters. Return a String made up of the string parameter concatenated with itself count time, where count is the integer. for example, if the parameters values are “ hi” and 4, the return value is “hihihihi” Return the original string if the integer parameter is less than 2.
What i have so Far
import java.util.Scanner;
public class Methods_4_16 {
public static String multiConcat(int Print, String Text){
String Msg;
for(int i = 0; i < Print; i ++ ){
}
return(Msg);
}
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
int Prints;
String Texts;
System.out.print("Enter Text:");
Texts = Input.nextLine();
System.out.print("Enter amount you wanted printed:");
Prints = Input.nextInt();
System.out.print(multiConcat(Prints,Texts));
}
}
Just a few hints:
concating strings can be done this way: appendTo += stuffToConcat
repeating an operation n times can be done with a for-loop of this kind:
for(int i = 0 ; i < n ; i++){
//do the stuff you want to repeat here
}
Should be pretty simple to build the solution from these two parts. And just in case you get a NullPointerException: remember to initialize Msg.
Try this:
public static String multiConcat(int print, String text){
StringBuilder msg = new StringBuilder();
for(int i = 0; i < print; i ++ ) {
msg.append(text);
}
return msg.toString();
}
I have used StringBuilder instead of a String. To know the difference, give this a read: String and StringBuilder.
Also, I would guess you are new to Java programming. Give this link a read. It is about Java naming conventions.
Hope this helps!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying write a program that accept an input and present the input with every 5th character replaced with X (count spaces also).
For example:
input: "hello my name is mario"
outpu: "hellX my Xame Xi maXio"
I only manage to replace specific letters, e.g every "m" letter.
Any help?
If you don't care about which character is at each fifth position you could use a regex.
String input = "hello my name is mario";
String output = input.replaceAll("(....).", "$1X");
System.out.printf("input : %s%noutput: %s%n", input, output);
output
input : hello my name is mario
output: hellX my Xame Xs maXio
Here is the code for you:
String test = "hello my name is mario";
String result = "";
int c = 1;
for (int i = 0; i < test.length(); i++) {
if (c++==5) {
result += "X";
c = 1;
} else {
result += test.charAt(i);
}
}
System.out.println("result = " + result);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So I am trying to prompt the user to enter any words into a string. Then I want to prompt them to count the number of occurrences for whatever letter they want to count. So if they enter words in a string like "this is a test" and they search "t" for example, the return would be 3 t's in the string "this is a test". I am a little confused as to where to go from here...
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputValue;
String s = "";
System.out.print("Enter a string of words or type done to exit: ");
inputValue = input.readLine();
System.out.print("Which letter would you like to count: ");
s = input.readLine();
int counter = 0;
I am thinking about maybe doing a for loop and do something like counter++.
Answer provided by Jean above is correct but I would like use a different method to calculate number of occurrence of a character in a String.
String string = "this is a testing string";
int count = string.length() - string.replaceAll("t", "").length();
Or
int counter = string.split("t").length - 1;
You would need to escape meta characters if you are to check character like $.
Using Apache commons-lang you could simply do
int counter = StringUtils.countMatches(s, intputValue);
But if you really want to code it, then you could use
public int count(String fullString, char valueToCount)
{
int count = 0;
for (int i=0; i < fullString.length(); i++)
{
if (fullString.charAt(i) == valueToCount)
count++;
}
return count;
}
Another solution would consist of replacing everything in your string except the input char and return the length of the trimmed string.
return s.replaceAll("[^" + inputValue + "]", "").length();