STEP WEEK 2 LAB PROBLEMS
H R S ARUL
RA2411026010548
AJ-1
1. import java.util.Scanner;
public class SimpleReplace {
public static String manualReplace(String text, String toFind, String toReplace) {
StringBuilder result = new StringBuilder();
int i = 0;
while (i <= text.length() - toFind.length()) {
if (text.substring(i, i + toFind.length()).equals(toFind)) {
result.append(toReplace);
i += toFind.length();
} else {
result.append(text.charAt(i));
i++;
}
}
result.append(text.substring(i));
return result.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter text: ");
String text = sc.nextLine();
System.out.print("Find: ");
String toFind = sc.nextLine();
System.out.print("Replace with: ");
String toReplace = sc.nextLine();
String manual = manualReplace(text, toFind, toReplace);
String builtIn = text.replace(toFind, toReplace);
System.out.println("Manual: " + manual);
System.out.println("Built-in: " + builtIn);
System.out.println("Match: " + manual.equals(builtIn));
sc.close();
}
}
2. import java.util.Scanner;
public class CaseConverter {
static char toUpper(char c) {
return (c >= 'a' && c <= 'z') ? (char)(c - 32) : c;
}
static char toLower(char c) {
return (c >= 'A' && c <= 'Z') ? (char)(c + 32) : c;
}
static String toUpperCase(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) sb.append(toUpper(c));
return sb.toString();
}
static String toLowerCase(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) sb.append(toLower(c));
return sb.toString();
}
static String toTitleCase(String s) {
StringBuilder sb = new StringBuilder();
boolean newWord = true;
for (char c : s.toCharArray()) {
if (c == ' ') {
sb.append(c);
newWord = true;
} else {
sb.append(newWord ? toUpper(c) : toLower(c));
newWord = false;
}
}
return sb.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter text: ");
String input = sc.nextLine();
String upper = toUpperCase(input);
String lower = toLowerCase(input);
String title = toTitleCase(input);
System.out.println("\n| Case | Result");
System.out.println("|------------|------------------------");
System.out.println("| UPPERCASE | " + upper);
System.out.println("| lowercase | " + lower);
System.out.println("| Title Case | " + title);
sc.close();
}
}
3. import java.util.*;
public class PerfTest {
static long testConcat(int n) {
long t = System.currentTimeMillis();
String s = "";
for (int i = 0; i < n; i++) s += "a";
return System.currentTimeMillis() - t;
}
static long testBuilder(int n) {
long t = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) sb.append("a");
return System.currentTimeMillis() - t;
}
static long testBuffer(int n) {
long t = System.currentTimeMillis();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n; i++) sb.append("a");
return System.currentTimeMillis() - t;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Iterations: ");
int n = sc.nextInt();
System.out.println("\n| Method | Time (ms)");
System.out.println("|--------------|-----------");
System.out.println("| String | " + testConcat(n));
System.out.println("| StringBuilder| " + testBuilder(n));
System.out.println("| StringBuffer | " + testBuffer(n));
sc.close();
}
}
4. import java.util.*;
public class CaesarCipher {
static String encrypt(String text, int shift) {
StringBuilder res = new StringBuilder();
for (char c : text.toCharArray()) {
if (c >= 'A' && c <= 'Z')
res.append((char) ('A' + (c - 'A' + shift) % 26));
else if (c >= 'a' && c <= 'z')
res.append((char) ('a' + (c - 'a' + shift) % 26));
else res.append(c);
}
return res.toString();
}
static String decrypt(String text, int shift) {
return encrypt(text, 26 - (shift % 26));
}
static void showAscii(String label, String text) {
System.out.print(label + ": ");
for (char c : text.toCharArray())
System.out.print((int) c + " ");
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter text: ");
String input = sc.nextLine();
System.out.print("Shift value: ");
int shift = sc.nextInt();
String encrypted = encrypt(input, shift);
String decrypted = decrypt(encrypted, shift);
System.out.println("\nOriginal: " + input);
showAscii("ASCII", input);
System.out.println("Encrypted: " + encrypted);
showAscii("ASCII", encrypted);
System.out.println("Decrypted: " + decrypted);
System.out.println("Match: " + input.equals(decrypted));
sc.close();
}
}
5. import java.util.*;
public class EmailAnalyzer {
static boolean isValid(String email) {
int at = email.indexOf('@'), atLast = email.lastIndexOf('@');
if (at == -1 || at != atLast) return false;
String user = email.substring(0, at), domain = email.substring(at + 1);
int dot = domain.indexOf('.');
return !user.isEmpty() && !domain.isEmpty() && dot > 0;
}
static String[] extractParts(String email) {
int at = email.indexOf('@');
String user = email.substring(0, at);
String domain = email.substring(at + 1);
int dot = domain.lastIndexOf('.');
String domName = dot > 0 ? domain.substring(0, dot) : domain;
String ext = dot > 0 ? domain.substring(dot + 1) : "";
return new String[]{user, domain, domName, ext};
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter emails (comma separated): ");
String[] emails = sc.nextLine().split(",");
int validCount = 0, invalidCount = 0, userLenSum = 0;
Map<String, Integer> domainCount = new HashMap<>();
System.out.println("Email\tUsername\tDomain\tDomainName\tExtension\tValid");
for (String e : emails) {
e = e.trim();
boolean valid = isValid(e);
if (valid) {
validCount++;
String[] parts = extractParts(e);
userLenSum += parts[0].length();
domainCount.put(parts[1], domainCount.getOrDefault(parts[1], 0) + 1);
System.out.printf("%s\t%s\t%s\t%s\t%s\t%s\n", e, parts[0], parts[1], parts[2],
parts[3], "Yes");
} else {
invalidCount++;
System.out.printf("%s\t%s\n", e, "Invalid");
}
}
String mostCommonDomain = domainCount.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey).orElse("N/A");
double avgUserLen = validCount > 0 ? (double) userLenSum / validCount : 0;
System.out.println("\nSummary:");
System.out.println("Valid emails: " + validCount);
System.out.println("Invalid emails: " + invalidCount);
System.out.println("Most common domain: " + mostCommonDomain);
System.out.printf("Average username length: %.2f\n", avgUserLen);
sc.close();
}
}
6. import java.util.*;
public class TextFormatter {
static String[] getWords(String text) {
ArrayList<String> words = new ArrayList<>();
int start = 0;
for (int i = 0; i <= text.length(); i++) {
if (i == text.length() || text.charAt(i) == ' ') {
if (i > start) words.add(text.substring(start, i));
start = i + 1;
}
}
return words.toArray(new String[0]);
}
static List<String> justifyLeft(String[] words, int width) {
List<String> lines = new ArrayList<>();
StringBuilder line = new StringBuilder();
int count = 0;
int last = 0;
for (int i = 0; i < words.length; i++) {
if (count + words[i].length() + (i - last) > width) {
int spaces = width - count;
int gaps = i - last - 1;
StringBuilder sb = new StringBuilder();
if (gaps == 0) {
sb.append(words[last]);
for (int s = 0; s < spaces; s++) sb.append(' ');
} else {
int even = spaces / gaps;
int extra = spaces % gaps;
for (int w = last; w < i - 1; w++) {
sb.append(words[w]);
for (int s = 0; s < even + (w - last < extra ? 1 : 0); s++) sb.append(' ');
}
sb.append(words[i - 1]);
}
lines.add(sb.toString());
count = 0;
last = i;
}
count += words[i].length();
}
StringBuilder lastLine = new StringBuilder();
for (int i = last; i < words.length; i++) {
if (i > last) lastLine.append(' ');
lastLine.append(words[i]);
}
for (int s = lastLine.length(); s < width; s++) lastLine.append(' ');
lines.add(lastLine.toString());
return lines;
}
static List<String> centerAlign(List<String> lines, int width) {
List<String> centered = new ArrayList<>();
for (String line : lines) {
int padding = (width - line.trim().length()) / 2;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < padding; i++) sb.append(' ');
sb.append(line.trim());
while (sb.length() < width) sb.append(' ');
centered.add(sb.toString());
}
return centered;
}
static long timeStringBuilder(String[] words, int width) {
long start = System.nanoTime();
justifyLeft(words, width);
return System.nanoTime() - start;
}
static long timeStringConcat(String[] words, int width) {
long start = System.nanoTime();
List<String> lines = new ArrayList<>();
int count = 0, last = 0;
for (int i = 0; i < words.length; i++) {
if (count + words[i].length() + (i - last) > width) {
int spaces = width - count;
int gaps = i - last - 1;
String line = "";
if (gaps == 0) {
line = words[last];
for (int s = 0; s < spaces; s++) line += " ";
} else {
int even = spaces / gaps;
int extra = spaces % gaps;
for (int w = last; w < i - 1; w++) {
line += words[w];
for (int s = 0; s < even + (w - last < extra ? 1 : 0); s++) line += " ";
}
line += words[i - 1];
}
lines.add(line);
count = 0;
last = i;
}
count += words[i].length();
}
String lastLine = "";
for (int i = last; i < words.length; i++) {
if (i > last) lastLine += " ";
lastLine += words[i];
}
while (lastLine.length() < width) lastLine += " ";
lines.add(lastLine);
return System.nanoTime() - start;
}
static void display(List<String> lines) {
for (int i = 0; i < lines.size(); i++)
System.out.printf("%2d: %s | %d chars\n", i + 1, lines.get(i), lines.get(i).length());
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter text: ");
String text = sc.nextLine();
System.out.print("Line width: ");
int width = sc.nextInt();
String[] words = getWords(text);
System.out.println("\nLeft Justified:");
List<String> left = justifyLeft(words, width);
display(left);
System.out.println("\nCenter Aligned:");
List<String> center = centerAlign(left, width);
display(center);
long sbTime = timeStringBuilder(words, width);
long strTime = timeStringConcat(words, width);
System.out.printf("\nPerformance:\nStringBuilder: %d ns\nString concat: %d ns\n",
sbTime, strTime);
sc.close();
}
}