Java string strings
I have a Java problem.
I am trying to split a string when "" happens, for example a test of the abc clause. Then move the first letter in each word from first to last. I got moving a letter to work on the original line with
String text = JOptionPane.showInputDialog(null,"Skriv in en normal text:");
char firstLetter = text.charAt(0);
normal = text.substring(1,text.length()+0) + firstLetter;
So my question is, how would I split the string and then start moving letters around each part of the cut string?
Thanks in advance
a source to share
You don't need split
-tranform-join for this; replaceAll
can do it in one step.
String text = "Skriv in en normal text:";
text = text.replaceAll("(\\s*)(\\w)(\\w+)", "$1$3$2");
System.out.println(text);
// prints "krivS ni ne ormaln extt:"
Basically regex captures 3 groups:
\1 : (\s*) : any optional preceding whitespace
\2 : (\w) : the head portion of each "word"
\3 : (\w+) : any tail portion of each "word"
Then, when the replacement string makes it obvious and straightforward, you switch in \2
and \3
around.
So, it should be clear that replaceAll
with a capturing group is the best, most readable solution for this problem, but that this is a regex depends on the specification of the problem. Note that, for example, the above regex will convert text:
to extt:
(i.e., the colon is stored where it is).
The next variation breaks into spaces \s
and reorders the head / tail of any sequence of characters without spaces \s
. This should be identical to the current split(" ")
-transform-join solution :
String text = "bob: !@#$ +-";
text = text.replaceAll("(\\s*)(\\S)(\\S+)", "$1$3$2");
System.out.println(text);
// prints "ob:b @#$! -+"
This variation includes a sequence of word characters \w+
surrounded by a word boundary \b
. If that's what you want, then this is the simplest, most readable solution for the job.
String text = "abc:def!ghi,jkl mno";
text = text.replaceAll("\\b(\\w)(\\w+)\\b", "$2$1");
System.out.println(text);
// prints "bca:efd!hig,klj nom"
see also
a source to share
Store your stripped strings in an array, then loop over the array and replace each one:
String[] pieces = originalString.split(" ");
for (int i = 0; i < pieces.length; i++)
pieces[i] = pieces[i].subString(1) + pieces[i].charAt(0);
By the way, this will only get you started - it won't correctly handle cases where there is more than one space, single letter words, or any other special cases (because you didn't say what you wanted to do). You will have to handle them yourself.
a source to share
Use String.split to split the string. Then run your code for each part. You can concatenate the string again using StringBuilder and a loop.
a source to share
If performance is an issue, consider StringTokenizer
instead split
, StringTokenizer is much faster.
a source to share