Design a class to overload a function Joystring( ) as follows :
(i) void Joystring (String s, char ch1 char ch2) with one string argument and two character arguments that replaces the character argument ch1 with the character argument ch2 in the given string s and prints the new string.
Example:
Input value of s = “TECHNALAGY”
ch1=‘A’,
ch2=‘O’
Output: TECHNOLOGY
(ii) void Joystring (String s) with one string argument that prints the position of the first space and the last space of the given string s.
Example:
Input value of = “Cloud computing means Internet based computing”
Output: First index : 5
Last index : 36
(iii) void Joystring (String s1, String s2) with two string arguments that combines the two string with a space between them and prints the resultant string.
Example :
Input value of s1 =“COMMON WEALTH”
Input value of s2 =“GAMES”
Output: COMMON WEALTH GAMES
(use library functions)
Solution:
We have tried to do this code in 2 methods:
Method 1: Using library functions
Method 2: Without using library functions
Note: Use anyone of the methods.
public class Year2015Q1
{
// Method 1: Using library functions
void Joystring(String s,char ch1,char ch2)
{
String newStr="";
int len=s.length();
newStr=s.replace(ch1, ch2);
System.out.println(newStr);
}
void Joystring(String s)
{
int firstSpaceIndex=0,lastSpaceIndex=0;
firstSpaceIndex=s.indexOf(' ');
lastSpaceIndex=s.lastIndexOf(' ');
System.out.println("First Index: "+firstSpaceIndex);
System.out.println("Last Index: "+lastSpaceIndex);
}
void Joystring(String s1,String s2)
{
System.out.println(s1.concat(" ").concat(s2));
}
// Method 2: Without using library functions
void Joystring(String s,char ch1,char ch2)
{
String newStr="";
int len=s.length();
for(int i=0;i<len;i++)
{
char ch=s.charAt(i);
if(ch==ch1)
{
newStr=newStr+ch2;
}
else
{
newStr=newStr+ch;
}
}
System.out.println(newStr);
}
void Joystring(String s)
{
int len=s.length();
int firstSpaceIndex=0,lastSpaceIndex=0;
for(int i=0;i<len;i++)
{
char ch=s.charAt(i);
if(ch==' ')
{
firstSpaceIndex=i;
break;
}
}
for(int i=len-1;i>=0;i--)
{
char ch=s.charAt(i);
if(ch==' ')
{
lastSpaceIndex=i;
break;
}
}
System.out.println("First Index: "+firstSpaceIndex);
System.out.println("Last Index: "+lastSpaceIndex);
}
void Joystring(String s1,String s2)
{
System.out.println(s1+" "+s2);
}
public static void main(String[] args)
{
Year2015Q1 ob = new Year2015Q1();
ob.Joystring("TECHNALAGY",'A','O');
ob.Joystring("Cloud computing means Internet based computing");
ob.Joystring("COMMON WEALTH","GAMES");
}
}
Output:
No comments:
Post a Comment