[Go to site: main page, start]

0% found this document useful (0 votes)
9 views7 pages

Java String Manipulation Assignment

The document outlines a Java programming assignment focused on string manipulation and processing, including string creation, comparison, input handling, and text analysis. It consists of multiple problems that demonstrate various string methods and their applications, culminating in a text processor application. The assignment reflection highlights key learnings, challenges faced, and the total time spent on the project.

Uploaded by

sainithinpokala
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)
9 views7 pages

Java String Manipulation Assignment

The document outlines a Java programming assignment focused on string manipulation and processing, including string creation, comparison, input handling, and text analysis. It consists of multiple problems that demonstrate various string methods and their applications, culminating in a text processor application. The assignment reflection highlights key learnings, challenges faced, and the total time spent on the project.

Uploaded by

sainithinpokala
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

Java String Programming Assignment

Student Name: [Your Name]


Course: Computer Science - Java Programming
Date: August 18, 2025
Assignment: String Manipulation and Processing

Problem 1: String Creation and Manipulation

public class StringManipulation {


public static void main(String[] args) {
// Creating the same string "Java Programming" using 3 different methods

// 1. String literal
String str1 = "Java Programming";

// 2. new String() constructor


String str2 = new String("Java Programming");

// 3. Character array
char[] charArray = {'J','a','v','a',' ','P','r','o','g','r','a','m','m','i','n','g'};
String str3 = new String(charArray);

// Comparing strings using == and .equals()


[Link]("=== String Comparison Results ===");
[Link]("str1 == str2: " + (str1 == str2));
[Link]("[Link](str2): " + [Link](str2));
[Link]("str1 == str3: " + (str1 == str3));
[Link]("[Link](str3): " + [Link](str3));

[Link]("\nExplanation:");
[Link]("== compares memory references, while .equals() compares content");
[Link]("String literals share the same memory location in string pool");

// String with escape sequences


String quote = "Programming Quote:\n\t\"Code is poetry\" - Unknown\nPath: C:\\Java\\Projects";
[Link]("\n" + quote);
}
}
Problem 2: String Input and Processing

import [Link];

public class StringMethods {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Getting user input


[Link]("Enter your full name (First Last): ");
String fullName = [Link]();

[Link]("Enter your favorite programming language: ");


String programmingLanguage = [Link]();

[Link]("Enter a sentence about your programming experience: ");


String sentence = [Link]();

// Processing the input

// 1. Extract first and last name separately


String[] nameParts = [Link](" ", 2);
String firstName = [Link] > 0 ? nameParts[^1_0] : "";
String lastName = [Link] > 1 ? nameParts[^1_1] : "";

// 2. Count total characters in sentence (excluding spaces)


String sentenceNoSpaces = [Link](" ", "");
int charCount = [Link]();

// 3. Convert programming language to uppercase


String langUpperCase = [Link]();

// 4. Display formatted summary


[Link]("\n=== SUMMARY ===");
[Link]("First Name: " + firstName);
[Link]("Last Name: " + lastName);
[Link]("Favorite Language: " + langUpperCase);
[Link]("Experience: " + sentence);
[Link]("Characters in experience (no spaces): " + charCount);

[Link]();
}
}

Problem 3: String Arrays and Methods

public class StringArrays {

// Method to find the longest name


public static String findLongestName(String[] names) {
if ([Link] == 0) return "";

String longest = names[^1_0];


for (String name : names) {
if ([Link]() > [Link]()) {
longest = name;
}
}
return longest;
}

// Method to count names starting with given letter (case-insensitive)


public static int countNamesStartingWith(String[] names, char letter) {
int count = 0;
char lowerLetter = [Link](letter);

for (String name : names) {


if ([Link]() > 0 && [Link]([Link](0)) == lowerLetter) {
count++;
}
}
return count;
}

// Method to format names to "Last, First" format


public static String[] formatNames(String[] names) {
String[] formattedNames = new String[[Link]];

for (int i = 0; i < [Link]; i++) {


String[] parts = names[i].split(" ", 2);
if ([Link] == 2) {
formattedNames[i] = parts[^1_1] + ", " + parts;
} else {
formattedNames[i] = names[i]; // Keep original if no space found
}
}
return formattedNames;
}

public static void main(String[] args) {


String[] students = {"John Smith", "Alice Johnson", "Bob Brown",
"Carol Davis", "David Wilson"};

// Testing all methods


[Link]("=== STRING ARRAY METHODS TEST ===");
[Link]("Original names:");
for (String student : students) {
[Link]("- " + student);
}

[Link]("\nLongest name: " + findLongestName(students));


[Link]("Names starting with 'D': " + countNamesStartingWith(students, 'D'));
[Link]("Names starting with 'B': " + countNamesStartingWith(students, 'B'));
[Link]("\nFormatted names (Last, First):");
String[] formatted = formatNames(students);
for (String name : formatted) {
[Link]("- " + name);
}
}
}

Problem 4: Complete String Application

import [Link];
import [Link];

public class TextProcessor {

// Method to clean and validate input


public static String cleanInput(String input) {
if (input == null) return "";

// Remove extra spaces and trim


String cleaned = [Link]().replaceAll("\\s+", " ");

// Convert to proper case (first letter of each sentence capitalized)


StringBuilder result = new StringBuilder();
boolean capitalizeNext = true;

for (char c : [Link]()) {


if (capitalizeNext && [Link](c)) {
[Link]([Link](c));
capitalizeNext = false;
} else {
[Link]([Link](c));
if (c == '.' || c == '!' || c == '?') {
capitalizeNext = true;
}
}
}

return [Link]();
}

// Method to analyze text


public static void analyzeText(String text) {
[Link]("\n=== TEXT ANALYSIS ===");

// Count words
String[] words = [Link]("\\s+");
[Link]("Word count: " + [Link]);

// Count sentences (approximate)


int sentences = [Link]("[.!?]+").length;
[Link]("Sentence count: " + sentences);

// Count characters (including spaces)


[Link]("Total characters: " + [Link]());

// Find longest word


String longestWord = "";
for (String word : words) {
String cleanWord = [Link]("[^a-zA-Z]", "");
if ([Link]() > [Link]()) {
longestWord = cleanWord;
}
}
[Link]("Longest word: " + longestWord);

// Find most common character (excluding spaces)


int[] charCount = new int[^1_256];
char mostCommon = ' ';
int maxCount = 0;

for (char c : [Link]()) {


if (c != ' ') {
charCount[c]++;
if (charCount[c] > maxCount) {
maxCount = charCount[c];
mostCommon = c;
}
}
}
[Link]("Most common character: '" + mostCommon + "' (appears " + maxCount + "
times)");
}

// Method to create sorted word array


public static String[] getWordsSorted(String text) {
String[] words = [Link]("\\s+");

// Remove punctuation and convert to lowercase


for (int i = 0; i < [Link]; i++) {
words[i] = words[i].replaceAll("[^a-zA-Z]", "").toLowerCase();
}

// Sort alphabetically
[Link](words);

return words;
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

[Link]("=== TEXT PROCESSOR ===");


[Link]("Enter a paragraph of text to process:");
String inputText = [Link]();

// Clean and validate input


String cleanedText = cleanInput(inputText);
[Link]("\nCleaned text: " + cleanedText);

// Analyze the text


analyzeText(cleanedText);

// Show words in alphabetical order


[Link]("\n=== WORDS IN ALPHABETICAL ORDER ===");
String[] sortedWords = getWordsSorted(cleanedText);
for (String word : sortedWords) {
if (![Link]()) {
[Link]("- " + word);
}
}

// Word search functionality


[Link]("\n=== WORD SEARCH ===");
[Link]("Enter a word to search for: ");
String searchWord = [Link]().toLowerCase();

boolean found = false;


for (String word : sortedWords) {
if ([Link](searchWord)) {
found = true;
break;
}
}

if (found) {
[Link]("✓ Word '" + searchWord + "' found in the text!");
} else {
[Link]("✗ Word '" + searchWord + "' not found in the text.");
}

[Link]();
[Link]("\nThank you for using Text Processor!");
}
}

Assignment Reflection

This assignment helped me understand various aspects of Java String manipulation:

1. String Creation Methods: I learned the difference between string literals (stored
in string pool), constructor method, and character array conversion.
2. String Comparison: The distinction between == (reference comparison) and
.equals() (content comparison) is crucial for proper string handling.

3. String Methods: Practiced using essential methods like split(), replace(),


toUpperCase(), trim(), and charAt().

4. Array Processing: Implemented methods to process string arrays effectively,


including sorting and filtering operations.

5. Real-world Application: The text processor demonstrates practical use of string


manipulation in building useful applications.

Challenges faced:

 Handling edge cases in string splitting and formatting

 Implementing proper text cleaning with regex patterns

 Managing memory efficiency in string operations

Key Learnings:

 Strings are immutable in Java

 StringBuilder is more efficient for multiple string modifications

 Regular expressions are powerful for text processing

 Input validation is essential for robust applications

Total Time Spent: 3 hours


Compilation Status: All programs compiled and tested successfully

Common questions

Powered by AI

StringBuilder is more efficient for scenarios involving extensive modifications, such as appending, inserting, or reversing strings, since it allows changes without creating new objects for each operation. This results in reduced memory allocation and improved performance, especially in large-scale text processing tasks .

Identify the most common character by iterating through the string, maintaining a frequency array, and excluding spaces. The character with the highest count, excluding spaces, is determined as most common. Consider efficiency by handling case insensitivity and ignoring non-letter characters .

Escape sequences like '\n' and '\t' add special characters, such as new lines or tabs, into strings, helping format them for better readability. An example from the document is the string 'Programming Quote:\n\t"Code is poetry" - Unknown\nPath: C:\\Java\\Projects', which uses '\n' for a new line and '\t' for a tab .

Strings in Java can be created using literals, through the new String() constructor, or by converting a character array. String literals are stored in the string pool, which optimizes memory usage as identical literals are shared. In contrast, the new String() constructor creates a new object every time in the heap, which uses more memory, whereas character arrays converted to strings are also stored as separate objects .

Use '.split()' to extract words, '.replaceAll()' to remove non-letter characters, '.toLowerCase()' to ignore casing, and 'Arrays.sort()' for sorting. This method addresses challenges like punctuation removal and casing inconsistencies, ensuring an accurately ordered word array .

The '==' operator compares the memory references of two string objects, causing it to return true only if both are the same object. In contrast, the '.equals()' method compares the content of the strings, returning true if the content is identical, regardless of their address in memory .

String manipulation skills directly translate into building applications like text editors or data parsers, where operations such as formatting, parsing, or searching are crucial. The assignment's 'Text Processor' is a practical example where one processes and analyzes text systematically, enhancing understanding of a real-world application .

Challenges include handling multiple spaces, no spaces in expected patterns, or unusual input like names with single parts. Adequate validations and conditions must be in place to manage such occurrences, using methods like '.split()' with edge cases for robustness .

An effective approach involves trimming the input to remove leading and trailing spaces and replacing multiple spaces with a single space using regex. To enhance readability, capitalize the first letter of each sentence by tracking sentence-ending punctuation marks and adjusting subsequent letters accordingly .

Effectively processing user input involves using 'Scanner' to obtain input and methods like '.split()' for separating strings like names, '.replace()' to remove spaces, '.toUpperCase()' for changing casing, and '.length()' to count non-space characters. Each method addresses a specific aspect of the processing task .

You might also like