0% found this document useful (0 votes)
32 views17 pages

Java String Manipulation Examples

The document contains 13 questions related to string operations in Java. Each question provides sample code to perform a specific string operation, such as converting a string to a character array, appending strings, finding string length, checking for substrings, sorting strings, generating passwords from names and numbers, rearranging characters in alphabetical order, extracting substrings, deleting characters, and checking for palindromes. The code examples demonstrate various string and string builder/buffer methods in Java like toCharArray(), concat(), trim(), indexOf(), split(), sort(), insert(), append(), replace(), delete(), and toString().

Uploaded by

subham
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views17 pages

Java String Manipulation Examples

The document contains 13 questions related to string operations in Java. Each question provides sample code to perform a specific string operation, such as converting a string to a character array, appending strings, finding string length, checking for substrings, sorting strings, generating passwords from names and numbers, rearranging characters in alphabetical order, extracting substrings, deleting characters, and checking for palindromes. The code examples demonstrate various string and string builder/buffer methods in Java like toCharArray(), concat(), trim(), indexOf(), split(), sort(), insert(), append(), replace(), delete(), and toString().

Uploaded by

subham
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

QUESTION – 1:-

Take a sting from keyboard and convert into character array (new one).

CODE:-
import [Link].*;

public class Stringchar {

public static void main(String args[])

Scanner sc = new Scanner([Link]);

String str = [Link]();

char[] ch = [Link]();

for (char c : ch) {

[Link](c+",");

OUTPUT:-
QUESTION – 2:-

Take a string from keyboard and a char array (filled up to length 5). Now
append the string to that char array. Show the char array.

CODE:-
import [Link].*;
public class Stringchara {
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
String str = [Link]();
char[] a = [Link]().toCharArray();
String str2= [Link](a);
String str3= str+ str2;
char[] ch = [Link]();
for (char c : ch) {
[Link](c+",");
}
}
}
OUTPUT:-

QUESTION – 3:-
Find length of a string taken from keyboard and also find the length of
that string except front and end spaces.

CODE:-
import [Link].*;
public class Stringlength {
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
String str = [Link]();
[Link]([Link]());
String str2 =[Link]();
[Link]([Link]());
}
}
OUTPUT:-

QUESTION – 4:-
Check if "Tech" presents in "University of Technology" or not. If yes
return its position.

CODE:-
import [Link].*;
public class Stringpos {
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
String str1 = [Link]();
String str2 = [Link]();
[Link]("position= "+[Link](str2));
}
}OUTPUT:-

QUESTION – 5:-
Write a program to take a sentence and convert it into string arrays and
sort the words using any sorting technique.
CODE:-
import [Link].*;
public class Stringsort {
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
String str;
[Link]("enter the string");
str=[Link]();
String strArray[] = [Link](" ");
[Link]("String : " + str);
[Link]("String array : [ ");
for (int i = 0; i < [Link]; i++) {
[Link](strArray[i] + ", ");
}
[Link]("]");
[Link]();
[Link](strArray);
[Link]("sorted:");
for (int i = 0; i < [Link];i++){
[Link](strArray[i]);
}
}
}

OUTPUT:-
QUESTION – 6:-
Generate password from initials of one’s first_name, middle_name,
last_name and with last four digit of your roll_no (if middle name is not
present, it won't come).
CODE:-
import [Link].*;
import [Link].*;
import [Link].*;
public class GeneratePassword {
String fname;
String mname;
String lname;
String rollno;

GeneratePassword(String f,String m,String l,String r) {


[Link]=f;
[Link]=m;
[Link]=l;
[Link]=r;
generatepassword();
}

GeneratePassword(String f,String l,String r){


[Link]=f;
[Link]=l;
[Link]=r;
generatepassword();
}
void generatepassword() {
String no;
if(mname==null) {
String f=[Link]([Link](0));
String l=[Link]([Link](0));
no = [Link]([Link]([Link]()-1))
+[Link]([Link]([Link]()-2))
+[Link]([Link]([Link]()-
3))+[Link]([Link]([Link]()-4));
no = new StringBuffer(no).reverse().toString();
String result=f + l + no;
[Link]("the password is: " + result);
}
else {
String f=[Link]([Link](0));
String l=[Link]([Link](0));
String m=[Link]([Link](0));
no= [Link]([Link]([Link]()-1))
+[Link]([Link]([Link]()-2))
+[Link]([Link]([Link]()-3))
+[Link]([Link]([Link]()-4));
no = new StringBuffer(no).reverse().toString();
String result2=f + m + l + no;
[Link]("the password is: " + result2);
}
}
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
[Link]("does your name has middle name");
String response=[Link]();
if([Link]("yes")) {
[Link]("enter first name");
String f=[Link]();
[Link]("enter middle name");
String m=[Link]();
[Link]("enter last name");
String l=[Link]();
[Link]("enter roll no");
String r=[Link]();
GeneratePassword g1=new GeneratePassword(f,m,l,r);
}
else {
[Link]("enter first name");
String f=[Link]();
[Link]("enter last name");
String l=[Link]();
[Link]("enter roll no");
String r=[Link]();
GeneratePassword g1=new GeneratePassword(f,l,r);
}
}
}

OUTPUT:-

QUESTION – 7:-
Write a program in Java which will read a string and rewrite it in the
alphabetical
order. For example, the word STRING should be written as GINRST.

CODE:-
import [Link];
import [Link];
public class wordsort {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string value: ");
String str = [Link]();
char charArray[] = [Link]();
[Link](charArray);
[Link](new String(charArray));
}
}

OUTPUT:-

QUESTION – 8:-
Write a program in Java to extract a portion of a character string and print
the
extracted string. Assume that m characters are extracted, starting with the
n-th
character. The method signature will be like void extract(String str, int n,
int m).
CODE:-
import [Link].*;
public class Extractpor{
static void extract(String str, int n, int m){
String newstr="";
while(m-- > 0){
newstr=newstr+[Link](n++);
}
[Link](newstr);
}
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
String inp;
int n,m;
inp=[Link]();
n=[Link]();
m=[Link]();
extract(inp,n-1,m);
}}

OUTPUT:-

QUESTION – 9:-
Write your own method is having a signature like String deleteMe(String
str, int m) that returns the input string with the m-th element removed.
CODE:-
import [Link].*;
public class delete
{
static String deleteMe(String str, int m)
{
String newstr="";
int i=0;
while(i<[Link]())
{
if(i+1==m)
{
i++;
continue;
}
newstr=newstr+[Link](i);
i++;
}
return newstr;
}
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
String inp;
int m;
inp=[Link]();
m=[Link]();
[Link](deleteMe(inp,m));
}
}
OUTPUT:-
QUESTION – 10:-

10. Write a program to do the following


i) To output the question “Who is the inventor of Java”?
ii) To accept an answer.
iii) To print out “Good” and then stop, if the answer is correct.
iv) To output the message “Try Again” and then stop, if the answer is wrong.
v) To display the correct answer when the answer is wrong even at the third
attempts and stop.
CODE:-
import [Link].*;
public class question
{
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
String ans;
int attempt=1;
while(attempt<=3)
{
[Link]("Who is the inventor of Java?");
ans=[Link]();
if([Link]("James Gosling"))
[Link]("Good");
else{
[Link]("Try Again");
attempt++;
}
}
if(attempt>3)
[Link]("Correct Answer: James Gosling");
}
}
OUTPUT:-
QUESTION – 11:-

Show that the String class type objects are immutable but StringBuffer class
objects
CODE:-
class ImmutableMutable{
public static void main(String args[]){
String s="Object Oriented";
[Link](" Programming");
[Link](s);
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");
[Link](sb);
}
}
OUTPUT:-
QUESTION – 12:-

Write a program in Java to create a StringBuffer object with content “Object


Programming languages”. Then perform the following operations
i) Print the object and determine its length and capacity.
ii) Inset a new string “Oriented” after the word “Object”. Print the modified
string.
iii) Insert a character ‘-’ at the 6-th position. Print the modified string again.
iv) Append another string named “ are very popular.” Print the resulting string.
v) Now delete the character ‘-’ and put a space (“ ”) there. Print it.
vi) Apply these operations one-by-one (a) delete(1, 7), (b) delete(2, 10), and
(c) delete(3, 13). Then print the result.
vii) Convert the StringBuffer type object into a String object. Print the final
result.
CODE:-
public class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Object Programming languages\n");
[Link]("\ncapacity: " + [Link]());
[Link]("length = " + [Link]());
[Link](sb);
char cArr[] = { 'O', 'r', 'i', 'e', 'n', 't', 'e', 'd',' ' };
[Link](7, cArr);
[Link]([Link]());
[Link](5,'-');
[Link]([Link]());
[Link]("are very popular.");
[Link](sb);
[Link](5, 6, " ");
[Link](sb);
[Link](1,7);
[Link](sb);
[Link](2,10);
[Link](sb);
[Link](3,13);
[Link](sb);
[Link]([Link]());
} }
OUTPUT:-
QUESTION – 13:-

Write a program in Java that checks whether a given string is a palindrome or


not. Ignore the cases.
CODE:-
import [Link];
public class Palindrome
{
public static void main(String args[])
{
String a, b = "";
Scanner s = new Scanner([Link]);
[Link]("Enter the string you want to check:");
a = [Link]();
int n = [Link]();
for(int i = n - 1; i >= 0; i--)
{
b = b + [Link](i);
}
if([Link](b))
{
[Link]("The string is palindrome.");
}
else
{
[Link]("The string is not palindrome.");
}
}
}

OUTPUT:-

Common questions

Powered by AI

String objects in Java are immutable; when a string is altered, a new string object is created rather than modifying the original. For example, calling `concat()` does not change the original string. Conversely, StringBuffer objects are mutable; methods like `append()` directly alter the original object without creating a new one, allowing for more efficient modifications .

To insert new content into a StringBuffer object at a specific position, the `insert()` method is utilized. This method takes an index and the string or character to be inserted. It modifies the StringBuffer object directly, as seen in the example where new characters were inserted after specified indices .

A StringBuffer object can be converted to a String object using the `toString()` method. This method returns a string representation of the data in the StringBuffer, effectively converting it into a String object .

To extract a specified portion of a string between two indexed positions, you can use a loop to iterate starting from the n-th character and append m characters to a new string. The loop continues until the desired number of characters has been added to the new string, as demonstrated by the `extract` method .

The password generation process involves taking the initials of the first, middle, and last names, if a middle name is present. The process also involves obtaining the last four digits of the roll number, which are reversed to maintain a specific format. The initials are concatenated with the reversed digits to form the password, demonstrating string and character manipulation capabilities in Java .

The characters of a string can be sorted alphabetically in Java by first converting the string to a character array using the `toCharArray()` method. The `Arrays.sort()` method is then applied to this character array, sorting the characters in place. Finally, a new string is constructed from the sorted character array .

The method used to find the position of a substring within a larger string in Java is `indexOf()`. This method returns the index within the string of the first occurrence of the specified substring. If the substring is not present, the method returns -1 .

To check if a string is a palindrome in Java, ignoring case sensitivity, the string is compared with its reverse. The reverse is obtained by iterating over the original string from end to start and constructing another string. The `equalsIgnoreCase()` method is used to compare the original string with its reversed version, as case differences are ignored .

To remove a specific character based on its index in a string, you can iterate over the string and construct a new string by skipping the character at the specified index. This is done using a loop to append each character to a new string except the character to be removed .

The program reads a string from the keyboard using a Scanner object. It then converts this string into a character array using the `toCharArray()` method provided by the String class. This method creates a new character array containing the characters of the string. The program iterates over the array and outputs each character followed by a comma .

You might also like