Copying characters in a string - java

i am trying to delete every digit from a string and then copy the letter that comes after that digit.
So for example the string 4a2b should output aaaabb.
So far my code looks like this:
Scanner scan= new Scanner(System.in);
String s = scan.nextLine();
String newString = s.replace(" ", "");
newString=newString.replaceAll("\\W+", "");
newString=newString.replaceAll("\\d+", "");
System.out.println(newString);
Is it possible to use regex and replaceAll to do that?

Try,
String newString = "4a2b";
String num = "";
StringBuilder res = new StringBuilder();
for (int i = 0; i < newString.length(); i++) {
char ch = newString.charAt(i);
if (Character.isDigit(ch)) {
num += ch;
} else if (Character.isLetter(ch)) {
if (num.length() > 0) {
for (int j = 0; j < Integer.parseInt(num); j++) {
res.append(ch);
}
}
num="";
}
}
System.out.println(res);

Try this:
public static void main(String[] args)
{
String str = "ae4a2bca";
Matcher m = Pattern.compile("(\\d+)(.)").matcher(str);
StringBuffer sb = new StringBuffer();
while (m.find())
{
m.appendReplacement(sb, times("$2", Integer.parseInt(m.group(1))));
}
m.appendTail(sb);
System.out.println(sb.toString());
}
private static String times(String string, int t)
{
String str = "";
for (int i = 0; i < t; ++i) str += string;
return str;
}

Related

Subsequence words

Suppose this is my .txt file ABCDBCD and I want to use .substring to get this:
ABC BCD CDB DBC BCD
How can I achieve this? I also need to stop the program if a line is shorter than 3 characters.
static void lesFil(String fil, subsekvens allHashMapSubsequences) throws FileNotFoundException{
Scanner scanner = new Scanner(new File("File1.txt"));
String currentLine, subString;
while(scanner.hasNextLine()){
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
for (int i = 0; i + subSize <= currentLine.length(); i++){
subString = currentLinje.substring(i, i + subSize);
subSekStr.putIfAbsent(subString, new subsequence(subString));
}
}
scanner.close();
With a minor changes of your code:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("C:\\Users\\Public\\File1.txt"));
String currentLine, subString;
int subSize = 3;
while (scanner.hasNextLine()) {
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
if (currentLine.length() < subSize) {
break;
}
for (int i = 0; i + subSize <= currentLine.length(); i++) {
subString = currentLine.substring(i, i + subSize);
System.out.print(subString + " ");
}
System.out.print("\n");
}
scanner.close();
}
This may be what you need
String str = "ABCDBCD";
int substringSize = 3;
String substring;
for(int i=0; i<str.length()-substringSize+1; i++){
substring = str.substring(i, i+substringSize);
System.out.println(substring);
}
import java.util.*;
public class Main
{
public static void main(String[] args) {
String input = "ABCDBCD";
for(int i = 0 ; i < input.length() ; i++) {
if(i < input.length() - 2) {
String temp = input.substring(i,i+3);
System.out.println(temp);
}
}
}
}

Swap the word in the String

input:-
1
Ans kot
Output:-
kot Ans
INPUT :
the first line of the input contains the number of test cases. Each test case consists of a single line containing the string.
OUTPUT :
output the string with the words swapped as stated above.**
Code:-
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
StringBuffer result = new StringBuffer();
for (int i = 0; i < a; i++) {
String b = sc.next();
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
}
What is wrong in my code ? above is code which i am trying.
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
this snippet of your code is only gonna reverse the sentence "word by word" not "character by character". therefore, you need reverse the string (my[j]) before you append it into the StringBuffer
Use this
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
sc.nextLine();
StringBuffer result = new StringBuffer();
for (int i = 0; i < a; i++) {
String b = sc.nextLine();
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
}
Multiple things:
You are using next api which will just read your string that you type word by word and you loop until a i.e. in your example just once. So instead use nextLine api which will read whole line instead of just a word and then split by space:
String b = sc.nextLine();
You are reading input with nextInt api followed by enter, you you might sometime end up having return character when reading next token using next api. Instead use:
int a = Integer.parseInt(sc.nextLine());
You are using StringBuffer which has an overhead of obtaining mutex and hence should use StringBuilder.
Takes String input and return String in reverse order of each characters.
String reverse(String x) {
int i = x.length() - 1;
StringBuilder y = new StringBuilder();
while (i >= 0) {
y.append(x.charAt(i));
i--;
}
return y.toString();
}
public static String reverseWords(String input) {
Deque<String> words = new ArrayDeque<>();
for (String word: input.split(" ")) {
if (!word.isEmpty()) {
words.addFirst(word);
}
}
StringBuilder result = new StringBuilder();
while (!words.isEmpty()) {
result.append(words.removeFirst());
if (!words.isEmpty()) {
result.append(" ");
}
}
return result.toString();
}
You can run this code:
String[] splitted = yourString.split(" ");
for (int i = splitted.length-1; i>=0; i--){
System.out.println(splitted[i]);
}
Code:-
Scanner sc =new Scanner(System.in);
int a =Integer.parseInt(sc.nextLine());
StringBuffer result= new StringBuffer();
for (int i = 0; i <a; i++) {
String b=sc.nextLine();
String my[]= b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length-1; j >0; j--) {
r.append(my[j]+" ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
enter code here

removing all character from string except a-z in array

i am trying to read words from the text file and store it in array.Problem from the code i tried as shown below is that it reads all characters such as "words," and "read." but i only want "words" and "read" in an array.
public String[] openFile() throws IOException
{
int noOfWords=0;
Scanner sc2 = new Scanner(new File(path));
while(sc2.hasNext())
{
noOfWords++;
sc2.next();
}
Scanner sc3 = new Scanner(new File(path));
String bagOfWords[] = new String[noOfWords];
for(int i = 0;i<noOfWords;i++)
{
bagOfWords[i] =sc3.next();
}
sc3.close();
sc2.close();
return bagOfWords;
}
Use regex replace :
replaceAll("([^a-zA-Z]+)","");
And apply that line to
bagOfWords[i] = sc3.next().replaceAll("([^a-zA-Z]+)","");
Use this code:
for (int i = 0; i < noOfWords; i++) {
bagOfWords[i] = sc3.next().replaceAll("[^A-Za-z0-9 ]", "");
}
You probably want only letters. In this case, you can use Character.isLetter(char) method.
Snippet:
String token = "word1";
String newToken = "";
for (int i = 0; i < token.length(); i++) {
char c = token.charAt(i);
if(java.lang.Character.isLetter(c)){
newToken += c;
}
}
System.out.println(newToken);

Count no of lines and words from string

I want to count the number of words and lines from a string content.
here is my code:
private int[] getLineAndWordCount(final String textContent) {
int wordCount = 0;
int lineCount = 0;
if (textContent.length() > 0) {
textContent = textContent.replace("\t", " ");
String[] newLineArrays = textContent.split("\n");
lineCount = newLineArrays.length;
for (String newLineStr : newLineArrays) {
String[] wordsArray = newLineStr.trim().split(" ");
for (String word : wordsArray) {
if (word.length() > 0) {
wordCount++;
}
}
}
}
return new int[]{lineCount, wordCount};
}
This codes works fine but during exceution it will create so many subStrings. So is there any other effective way to do the same thing. Thanks.
Try to use java.util.Scanner. For instance:
Scanner textScanner = new Scanner(text);
while (textScanner.hasNextLine()) {
linesCount++;
Scanner wordsScanner = new Scanner(textScanner.nextLine());
while (wordsScanner.hasNext()) {
wordsCount++;
wordsScanner.next();
}
}
A javadoc for java.util.Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
You can try this way.
Scanner scanner=new Scanner(new File("Location"));
int numberOfLines=0;
StringTokenizer stringTokenizer=null;
int numberOfWords=0;
while (scanner.hasNextLine()){
stringTokenizer=new StringTokenizer(scanner.nextLine()," ");
numberOfWords=numberOfWords+stringTokenizer.countTokens();
numberOfLines++;
}
System.out.println("Number of lines :"+numberOfLines);
System.out.println("Number of words :"+numberOfWords);
Usig Regex
String str = "A B C\n D E F\n";
Pattern compile = Pattern.compile("\n");
Matcher matcher = compile.matcher(str);
int count = 0;
while(matcher.find()){
count++;
}
System.out.println(count);//2
count=0;
Pattern compile1 = Pattern.compile("\\s+");
Matcher matcher1 = compile1.matcher(str);
while(matcher1.find()){
count++;
}
System.out.println(count);//6
You can also try this
int line=str.trim().split("\n").length;
int words=str.trim().split("\\s+").length;

In Java, how do you convert all of the words of a string to sentence case?

In Java, how do you convert this:
little bo peep HAS LOST HER SHEEP And Doesn't Know WHERE to Find them
to this:
Little Bo Peep Has Lost Her Sheep And Doesn't Know Where To Find Them
WordUtils.capitalizeFully(String input) from commons lang
public static void main(String[] args) {
String str = "little bo peep HAS LOST HER SHEEP And Doesn't Know WHERE to Find them";
str = str.toLowerCase();
final StringTokenizer st = new StringTokenizer(str, " ");
final StringBuilder sb = new StringBuilder();
while (st.hasMoreTokens()) {
String token = st.nextToken();
sb.append(Character.toUpperCase(token.charAt(0))
+ token.substring(1) + " ");
}
System.out.println(sb.toString().trim());
}
Or plain split version:
public static String capWords(String s) {
if (s == null && s.isEmpty()) {
return s;
} else {
StringBuilder sb = new StringBuilder();
for (String token : s.split(" ")) {
if (token.isEmpty()) {
if (sb.length() > 0) {
sb.append(" ");
}
} else {
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(Character.toUpperCase(token.charAt(0)));
if (token.length() > 1) {
sb.append(token.substring(1).toLowerCase());
}
}
}
return sb.toString();
}
}
Note: this version will also trim leading/trailing spaces (which may or may not be desired)
private static String capitalize(String s){
String str = s.toLowerCase();
char[] c = str.toCharArray();
c[0] = Character.toUpperCase(c[0]);
return new String(c);
}
private static String format(String s){
String[] splitted = s.split(" ");
StringBuffer sb = new StringBuffer();
for(int i=0, l = splitted.length; i < l; i++){
if(splitted[i].trim().length() != 0){
sb.append(capitalize(splitted[i]) + " ");
}
if(i != l-1){
sb.append(" ");
}
}
return sb.toString();
}
public static void main(String... args){
System.out.println(format("little bo peep HAS LOST HER SHEEP And Doesn't Know WHERE to Find them"));
}
import java.io.*;
class ex3
{
public static void main(String arg[])
{
DataInputStream dis = new DataInputStream(System.in);
try
{
System.out.println("ENTER THE STRING::");
String s=dis.readLine();
String res="";
char fchar=Character.toUpperCase(s.charAt(0));
res=res+fchar;
for(int i=1;i<=s.length()-1;i++)
{
if(s.charAt(i)==' ')
res=res+s.charAt(i);
else if(s.charAt(i)=='.'||s.charAt(i)=='?'||s.charAt(i)=='!')
{
res=res+s.charAt(i);
res=res+Character.toUpperCase(s.charAt(i+1));
i=i+1;
}
else
res=res+Character.toLowerCase(s.charAt(i));
}
System.out.println(res);
}
catch(Exception e){}
}
}

Categories

Resources