Solved

Core Java. String manipulation. In given string swap specific characters.

Posted on 2016-07-25
13
78 Views
Last Modified: 2016-07-27
There is a word. You need to swap ( replace by each other ) first letter "m" and the last letter "p" . Also you should consider the possibility that such letters won't be in a given word.



For example :

test1.
input : mamapapa
output: pamapama

test2
input: enormous
output: sorry there isn't any "p" letter in the word

test3
input: place
output: sorry there isn't any "m" letter in the word.

Many thxs in advance !
0
Comment
Question by:SunnyX
  • 5
  • 4
  • 2
  • +2
13 Comments
 
LVL 15

Expert Comment

by:gurpsbassi
ID: 41728377
Homework exercise?
0
 

Author Comment

by:SunnyX
ID: 41728822
no
0
 
LVL 37

Expert Comment

by:zzynx
ID: 41728853
Tell me in words (in pseudo code) how you would proceed with this task.
1
 

Author Comment

by:SunnyX
ID: 41728972
There isn't any optimization requirements here yet. So I come up with some simple idea. Please, help me to implement it.

1. First of we should take some method / function that help as to treat String like a char vector .
 mamapapa = > [ m, a, m, a, p, a, p, a ] 

Open in new window

2. then we implement loop to search for first "m" and remember index of this letter ... when the letter is detected break the loop
int i =0;
( for i ; i < ourCharVector.length() ; ++i ) 
{
(if ourCharVector[i] = "m" || ourCharVector[i] = "M")
{
break ; 
}
}

Open in new window


3. then second loop for detecting "p", because we need last one we shouldn't break at of loop
it will be something like

int k = 0 ; 
( for int j = 0 ; j < ourCharVector.length() ; ++j ) 
{
(if ourCharVector[i] = "p" || ourCharVector[i] = "P")
{
k = j ; 
}
}

Open in new window


4. after we detected indexes of needed letter we should implement some swap function or some buffer vector ...
outCharVector[i] = outBufferVector [0];
outCharVector[k] = outBufferVector [1];

Open in new window


5. and swap it
outCharVector[i] = outBufferVector [1];
outCharVector[k] = outBufferVector [0];

Open in new window


6. convert charvector to string again + handle exception somewhere ( if there is "m/p" ,  do something )...

Zzynx, I really wanna find better / more optimal solution to the problem. Actually,  this is the first that come to my mind, please, help. Thanks you for your time !
0
 
LVL 37

Assisted Solution

by:zzynx
zzynx earned 100 total points
ID: 41728991
I think you should keep it as simple as possible.

Use these two String methods to find the index of the first occurrence of 'm' and the index of the last occurrence of 'p':

indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
(cf. https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int))

lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character
(cf. https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#lastIndexOf(int))

Remark that this methods return -1 if the character doesn't occur.

Assume we have stored the result in the variables 'indexOfM' and 'indexOfP'.
(I guess you know what condition to output "Sorry there isn't any "p" letter in the word" or "sorry there isn't any "m" letter in the word")

If that is not the case, you can build up a StringBuffer, by adding all characters you find in the initially given string until you encounter index == indexOfM. If you encounter that index, you add a 'p'. You go on. If you encounter index == indexOfP you add a 'm'. Then you go on adding the rest of the characters.
Now the StringBuffer contains the requested result, so return yourStringBuffer.toString() and you're done.
1
 
LVL 35

Assisted Solution

by:mccarl
mccarl earned 50 total points
ID: 41729512
A slight variation to what @zzynx wrote above, use the indexOf methods mentioned but then you can use String.toCharArray to get a mutable array, set the new chars in the correct indexes and then use the correct String constructor to convert the array back to a String
1
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 32

Accepted Solution

by:
awking00 earned 350 total points
ID: 41729703
You might also consider using a StringBuilder with its deleteCharAt() and insert() methods -
StringBuilder sb = new StringBuilder("mamapapa");
midx = sb.indexOf("m");
pidx  = sb.lastIndexOf("p");
            if (midx >= 0 && pidx >= 0) {
                  sb.deleteCharAt(pidx).insert(pidx, "m");
                  sb.deleteCharAt(midx).insert(midx, "p");
                  System.out.println(sb.toString());
            }
            if (midx < 0) {
                  System.out.println("Sorry, there is no m in the string");
            }
            if (pidx < 0) {
                  System.out.println("Sorry, there is no p in the string");
            }
1
 

Author Comment

by:SunnyX
ID: 41731187
Thx to everybody ! much appreciated !
0
 

Author Closing Comment

by:SunnyX
ID: 41731188
Thx you once  again !
0
 
LVL 37

Expert Comment

by:zzynx
ID: 41731190
You're welcome. Thanx 4 axxepting.

However, it's a pitty and frustrating that someone posting full code - which I didn't want to do because of the nature of the question - based on my initial idea get most of the points.
1
 

Author Comment

by:SunnyX
ID: 41731302
Sorry it's my fault, I should clarify that your code will be much appreciated.
0
 
LVL 32

Expert Comment

by:awking00
ID: 41731322
zzynx, I only posted full code because SunnyX flatly said, "no" when asked if this homework exercise, although I agree the question did have that feel.
1
 
LVL 37

Expert Comment

by:zzynx
ID: 41731438
Sorry it's my fault, I should clarify that your code will be much appreciated.
??? I didn't post any code.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
PDFBox - convert image to PDF, PDF resolution 3 112
bitbucket vs gitbucket 3 55
session migration servlets 2 24
windows explorer path to command prompt 5 27
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This video teaches viewers about errors in exception handling.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

929 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now