How can I access each element of a string array in java? - java

I was writing a function to reverse the position of words in a string without reversing the words themselves.
But I am not able to access the elements of string array. I am getting error with the following code.
public static void reverseWords(String sd[]) {
for(String s : sd){
System.out.println(s);
}
}

To reverse the words in a String array do the following.
public class Reverse{
public static void main(String[] args){
String[] stringArray = {"Jim", "Jeff", "Darren", "Michael"};
reverseWords(stringArray);
for(String strings : stringArray) {
System.out.println(strings);
}
}
public static void reverseWords(String[] array) {
for(int i=0; i<array.length/2; i++) {
String temp = array[array.length-1-i];
array[array.length-1-i] = array[i];
array[i] = temp;
}
}
}
Output :
Michael
Darren
Jeff
Jim
To take in a String as an input try the following.
public class Reverse{
public static void main(String[] args){
String sentence = "Bob went to the store";
String newSentence = reverseWords(sentence);
System.out.println(newSentence);
}
public static String reverseWords(String sentence) {
//This line splits the String sentence by the delimiter " " or by a space
String[] array = sentence.split(" ");
//for loop to reverse the array
for(int i=0; i<array.length/2; i++) {
String temp = array[array.length-1-i];
array[array.length-1-i] = array[i];
array[i] = temp;
}
//These next 4 lines simply take each element in the array
//and concatenate them all into one String, reversedSentence.
String reversedSentence = "";
for(int i=0; i<array.length; i++) {
//This if statement ensures that no space (" ") is concatenated
//to the end of the reversedSentence.
if(i == array.length-1) {
reversedSentence += array[i];
continue;
}
reversedSentence += array[i] + " ";
}
//returning the newly created reversedSentence!
return reversedSentence;
}
}
Output :
store the to went Bob
Hope this helps!

Related

Java: Print a unique character in a string

I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.
Here's my code:
import java.util.Scanner;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
}
}
System.out.println(temp + " ");
}
}
And here's sample output with the above code:
Enter a word:
nreena
nrea
The expected output would be: ra
Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
How about applying the KISS principle:
public static void uniqueCharacters(String test) {
System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
The accepted answer will not pass all the test case for example
input -"aaabcdd"
desired output-"bc"
but the accepted answer will give -abc
because the character a present odd number of times.
Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveConductive {
public static void main(String[] args) {
String s="aabcddkkbghff";
String[] cvrtar=s.trim().split("");
ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
for(int i=0;i<cvrtar.length;i++){
if(!hm.containsKey(cvrtar[i])){
hm.put(cvrtar[i],1);
}
else{
hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
}
}
for(String ele:hm.keySet()){
if(hm.get(ele)>1){
hm.remove(ele);
}
}
for(String key:hm.keySet()){
System.out.print(key);
}
}
}
Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :
public static void uniqueCharacters(String test) {
String temp = "";
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
if (temp.indexOf(ch) == -1) {
temp = temp + ch;
} else {
temp.replace(String.valueOf(ch),""); // added this to your existing code
}
}
System.out.println(temp + " ");
}
This is an interview question. Find Out all the unique characters of a string.
Here is the complete solution. The code itself is self explanatory.
public class Test12 {
public static void main(String[] args) {
String a = "ProtijayiGiniGina";
allunique(a);
}
private static void allunique(String a) {
int[] count = new int[256];// taking count of characters
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch]++;
}
for (int i = 0; i < a.length(); i++) {
char chh = a.charAt(i);
// character which has arrived only one time in the string will be printed out
if (count[chh] == 1) {
System.out.println("index => " + i + " and unique character => " + a.charAt(i));
}
}
}// unique
}
In Python :
def firstUniqChar(a):
count = [0] *256
for i in a: count[ord(i)] += 1
element = ""
for item in a:
if (count[ord(item)] == 1):
element = item;
break;
return element
a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
public static void uniqueValue (String numbers) {
String [] str = input.split(" ");
Set <String> unique = new HashSet <String> (Arrays.asList(str));
System.out.println(unique);
for (String value:unique) {
int count = 0;
for ( int i= 0; i<str.length; i++) {
if (value.equals(str[i])) {
count++;
}
}
System.out.println(value+"\t"+count);
}
}
public static void main(String [] args) {
uniqueValue(input);
}
Step1: To find the unique characters in a string, I have first taken the string from user.
Step2: Converted the input string to charArray using built in function in java.
Step3: Considered two HashSet (set1 for storing all characters even if it is getting repeated, set2 for storing only unique characters.
Step4 : Run for loop over the array and check that if particular character is not there in set1 then add it to both set1 and set2. if that particular character is already there in set1 then add it to set1 again but remove it from set2.( This else part is useful when particular character is getting repeated odd number of times).
Step5 : Now set2 will have only unique characters. Hence, just print that set2.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String str = input.next();
char arr[] = str.toCharArray();
HashSet<Character> set1=new HashSet<Character>();
HashSet<Character> set2=new HashSet<Character>();
for(char i:arr)
{
if(set1.contains(i))
{
set1.add(i);
set2.remove(i);
}
else
{
set1.add(i);
set2.add(i);
}
}
System.out.println(set2);
}
I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.
public static void uniqueCharacters(String test) {
String temp = "";
char[] array = test.toCharArray();
int count; //keep track of how many times the character exists in the string
outerloop: for (int i = 0; i < test.length(); i++) {
count = 0; //reset the count for every new letter
for(int j = 0; j < array.length; j++) {
if(test.charAt(i) == array[j])
count++;
if(count == 2){
count = 0;
continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
}
}
temp += test.charAt(i);
System.out.println("Adding.");
}
System.out.println(temp);
}
I have added comments for some more detail.
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
If you don't want to use additional space:
String abc="developer";
System.out.println("The unique characters are-");
for(int i=0;i<abc.length();i++)
{
for(int j=i+1;j<abc.length();j++)
{
if(abc.charAt(i)==abc.charAt(j))
abc=abc.replace(String.valueOf(abc.charAt(j))," ");
}
}
System.out.println(abc);
Time complexity O(n^2) and no space.
This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.
static String printUniqChar(String s) {
StringBuilder buildUniq = new StringBuilder();
boolean[] uniqCheck = new boolean[128];
for (int i = 0; i < s.length(); i++) {
if (!uniqCheck[s.charAt(i)]) {
uniqCheck[s.charAt(i)] = true;
if (uniqCheck[s.charAt(i)])
buildUniq.append(s.charAt(i));
}
}
public class UniqueCharactersInString {
public static void main(String []args){
String input = "aabbcc";
String output = uniqueString(input);
System.out.println(output);
}
public static String uniqueString(String s){
HashSet<Character> uniques = new HashSet<>();
uniques.add(s.charAt(0));
String out = "";
out += s.charAt(0);
for(int i =1; i < s.length(); i++){
if(!uniques.contains(s.charAt(i))){
uniques.add(s.charAt(i));
out += s.charAt(i);
}
}
return out;
}
}
What would be the inneficiencies of this answer? How does it compare to other answers?
Based on your desired output you can replace each character already present with a blank character.
public static void uniqueCharacters(String test){
String temp = "";
for(int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
} else {
temp.replace(String.valueOf(temp.charAt(i)), "");
}
}
System.out.println(temp + " ");
}
public void uniq(String inputString) {
String result = "";
int inputStringLen = inputStr.length();
int[] repeatedCharacters = new int[inputStringLen];
char inputTmpChar;
char tmpChar;
for (int i = 0; i < inputStringLen; i++) {
inputTmpChar = inputStr.charAt(i);
for (int j = 0; j < inputStringLen; j++) {
tmpChar = inputStr.charAt(j);
if (inputTmpChar == tmpChar)
repeatedCharacters[i]++;
}
}
for (int k = 0; k < inputStringLen; k++) {
inputTmpChar = inputStr.charAt(k);
if (repeatedCharacters[k] == 1)
result = result + inputTmpChar + " ";
}
System.out.println ("Unique characters: " + result);
}
In first for loop I count the number of times the character repeats in the string. In the second line I am looking for characters repetitive once.
how about this :)
for (int i=0; i< input.length();i++)
if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
System.out.println(input.charAt(i) + " is unique");
package extra;
public class TempClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String abcString="hsfj'pwue2hsu38bf74sa';fwe'rwe34hrfafnosdfoasq7433qweid";
char[] myCharArray=abcString.toCharArray();
TempClass mClass=new TempClass();
mClass.countUnique(myCharArray);
mClass.countEach(myCharArray);
}
/**
* This is the program to find unique characters in array.
* #add This is nice.
* */
public void countUnique(char[] myCharArray) {
int arrayLength=myCharArray.length;
System.out.println("Array Length is: "+arrayLength);
char[] uniqueValues=new char[myCharArray.length];
int uniqueValueIndex=0;
int count=0;
for(int i=0;i<arrayLength;i++) {
for(int j=0;j<arrayLength;j++) {
if (myCharArray[i]==myCharArray[j] && i!=j) {
count=count+1;
}
}
if (count==0) {
uniqueValues[uniqueValueIndex]=myCharArray[i];
uniqueValueIndex=uniqueValueIndex+1;
count=0;
}
count=0;
}
for(char a:uniqueValues) {
System.out.println(a);
}
}
/**
* This is the program to find count each characters in array.
* #add This is nice.
* */
public void countEach(char[] myCharArray) {
}
}
Here str will be your string to find the unique characters.
function getUniqueChars(str){
let uniqueChars = '';
for(let i = 0; i< str.length; i++){
for(let j= 0; j< str.length; j++) {
if(str.indexOf(str[i]) === str.lastIndexOf(str[j])) {
uniqueChars += str[i];
}
}
}
return uniqueChars;
}
public static void main(String[] args) {
String s = "aaabcdd";
char a[] = s.toCharArray();
List duplicates = new ArrayList();
List uniqueElements = new ArrayList();
for (int i = 0; i < a.length; i++) {
uniqueElements.add(a[i]);
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
duplicates.add(a[i]);
break;
}
}
}
uniqueElements.removeAll(duplicates);
System.out.println(uniqueElements);
System.out.println("First Unique : "+uniqueElements.get(0));
}
Output :
[b, c]
First Unique : b
import java.util.*;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
for(int i=0;i<test.length();i++){
if(test.lastIndexOf(test.charAt(i))!=i)
test=test.replaceAll(String.valueOf(test.charAt(i)),"");
}
System.out.println(test);
}
}
public class Program02
{
public static void main(String[] args)
{
String inputString = "abhilasha";
for (int i = 0; i < inputString.length(); i++)
{
for (int j = i + 1; j < inputString.length(); j++)
{
if(inputString.toCharArray()[i] == inputString.toCharArray()[j])
{
inputString = inputString.replace(String.valueOf(inputString.charAt(j)), "");
}
}
}
System.out.println(inputString);
}
}

how to reverse the word using list iterator in java

class StringRev{
public static void main(String args[]){
String str = "He is the one";
String temp = "";
String finalString = "";
for(int i =str.length()-1;i>=0;i--){
temp +=i!=0?str.charAt(i):str.charAt(i)+" ";
if(str.charAt(i) == ' '||i==0){
for(int j=temp.length()-1;j>=0;j--){
finalString += temp.charAt(j);
}
temp = "";
}
}
System.out.println(finalString);
}
}
I tried to solve.I have to reverse the string "He is the one" to "one the is He".
I have written some programs in Java but am looking for other best solutions.
Suggest any possible ways to minimize the current.
Split the String into words and the iterate downwards and append the words back to a String.
public class StringRev{
public static void main(String args[]){
String input = "He is the one";
String output = "";
String[] inputSplit = input.split(" ");
for(int i=inputSplit.length-1; i>=0; i--){
output += inputSplit[i] + " ";
}
System.out.println(output.trim()); //remove trailing space
}
}
If you can use Collections and StringUtil then it's even more straight forward.
public class StringRev{
public static void main(String args[]){
String input = "He is the one";
String[] inputSplit = input.split(" ");
Collections.reverse(Arrays.asList(inputSplit));
String output = StringUtil.join(Arrays.asList(inputSplit), " ");
System.out.println(output);
}
}
Simply just split given string on spaces, will give you an array of words, iterate reversely and append it to new string as following:
String string = "He is the one";
System.out.println("Original String: " + string);
String[] arr = string.split(" ");
String reverseString = "";
for(int i = arr.length - 1; i >= 0; i--){
reverseString += arr[i] + " ";
}
System.out.println("Reverse String: " + reverseString);
OR you can use Arrays utility to convert split-ed string into List, make it reverse it using Collection utility reverse method, iterate over it and create string as following:
List<String> list = Arrays.asList(string.split(" "));
Collections.reverse(list);
String reserveStringUsingList = "";
for(String str : list){
reserveStringUsingList += str + " ";
}
System.out.println("Reverse String using List: " + reserveStringUsingList);
Here is the solution you asked for, using ListIterator:
Code:
public static void main(String[] args) {
final String str = "He is the one";
System.out.println(str);
System.out.println(reverseWords(str));
}
static String reverseWords(String str) {
StringBuilder result = new StringBuilder(str.length());
List<String> words = Arrays.asList(str.split(" "));
if(!words.isEmpty()) {
ListIterator<String> it = words.listIterator(words.size());
result.append(it.previous());
while (it.hasPrevious()) {
result.append(' ').append(it.previous());
}
}
return result.toString();
}
Output:
He is the one
one the is He

Getting error trying to reverse a string in Java

I'm trying to do a simple reverse task like: change the string "how are you" to "you are how".
this is my code:
public class Program {
public static String revSentence (String str) {
String [] givenString = str.split(" ");
String [] retString = new String[givenString.length];
int last = givenString.length - 1;
for (int i = 0; i < givenString.length; i++) {
retString [i] = givenString[last--];
}
return retString.toString();
}
public static void main(String[] args) {
String m = "how are you";
System.out.println(revSentence(m));
}
}
I'm getting a weird output:
[Ljava.lang.String;#e76cbf7
The output isn't "weird" at all - it's the Object's internal string representation, created by Object.toString(). String[] doesnt override that. If you want to output all entires, loop through them and concatenate them, Best using a StringBuilder to avoid creating unnecessary String instances.
public static String arrayToString (String[] array) {
StringBuilder result = new StringBuilder();
for (String value : array) {
result.append(value);
}
return StringBuilder.toString();
}
If you don'T need that method on it'S own and want to include it in the overall process of reversing the sentence, this is how it may look. It iterates only once, iterating backwards (= counting down) to reverse the sentence.
public static String revSentence (String str) {
String [] givenString = str.split(" ");
StringBuilder result = new StringBuilder();
// no need for 'last', we can use i to count down as well...
for (int i = givenString.length - 1 ; i >= 0; i--) {
result.append(givenString[i]);
}
return result.toString();
}
[Edit]: because of the OPs comment to one of the other answers, about not having learned how to use StringBUilder yet, here is a arrayToStirng method without using one. Note however that this should not be done normally, as it creates useless instances of String whiche are not cleaned up by the GC because of the immutable nature of String(all instances are kept for reuse).
public static String arrayToString (String[] array) {
String result = "";
for (String value : array) {
result += value;
}
return result;
}
Or, without a dedicate arrayToString method:
public static String revSentence (String str) {
String [] givenString = str.split(" ");
String result = "";
for (int i = givenString.length-1 ; i >= 0 ; i--) {
result += givenString[i];
}
return result;
}
Here is a solution:
public class Program {
public static String revSentence (String str) {
String retString = "";
String [] givenString = str.split(" ");
for (int i=givenString.length-1; i>=0; i--) {
retString += givenString[i] + " ";
}
return retString;
}
public static void main(String[] args) {
String m = "how are you";
System.out.print(revSentence(m));
}
}
Modified it to make the "revSentence" function return a String, plus improved the code a bit. Enjoy!
Calling toString() on an array object (in your case retString) doesn't print all array entries, instead it prints object address.
You should print array entries by iterating over them.
Use this code for reversed string
StringBuilder builder = new StringBuilder();
for(String s : retString) {
builder.append(s);
}
return builder.toString();
Calling toString on an array gives you the memory ref which isn't very useful. Try this:
public static String revSentence (String str) {
String[] givenString = str.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = givenString.length - 1; i >= 0; i--) {
sb.append(givenString[i]);
if (i != 0)
sb.append(" ");
}
return sb.toString();
}
the for loop start from greater length to lower and builder.append(givenString[i] + " "); this will concatenate String and return whole sentence you are how you could use both mySentence += givenString[i] + " "; or builder.append(givenString[i] + " "); but the best way is to use StringBuilder class (see docs)
public class Program {
public static String revSentence(String str) {
String[] givenString = str.split(" ");
String[] retString = new String[givenString.length];
int last = givenString.length - 1;
//String mySentence = "";
StringBuilder builder = new StringBuilder();
for (int i = givenString.length - 1; i >= 0; i--) {
// retString [i] = givenString[i];
// mySentence += givenString[i] + " ";
builder.append(givenString[i] + " ");
}
return builder.toString(); // retuning String
//return mySentence;
}
public static void main(String[] args) {
String m = "how are you";
System.out.println(revSentence(m));
}
}
Faster, and shorter:
To reverse a word, use:
public String reverseWord(String s) {
StringBuilder y = new StringBuilder(s);
return y.reverse();
}
Now split and use this method and use Stringbuidler.append to concatenate the all.
And dont forget the space inbetween.

Generating String Tokens in Java

I want to generate possible tokens using forward traversal in Java. For example if I have a string "This is my car". I need to generate tokens
"This is my car"
"This is my"
"This is"
"This"
"is my car"
"is my"
"is"
"my car"
"my"
"car"
What is the best way to do this? Any examples? Thanks.
Here is another solution with split and nested loops:
public static void main(String[] args) {
String original = "this is my car";
String[] singleWords = original.split(" "); // split the String to get the single words
ArrayList<String> results = new ArrayList<String>(); // a container for all the possible sentences
for (int startWord = 0; startWord < singleWords.length; startWord++) { // starWords start with 0 and increment just until they reach the last word
for (int lastWord = singleWords.length; lastWord > startWord; lastWord--) { // last words start at the end and decrement just until they reached the first word
String next = "";
for (int i = startWord; i != lastWord; i++) { // put all words in one String (starting with the startWord and ending with the lastWord)
next += singleWords[i] + " ";
}
results.add(next); // add the next result to your result list
}
}
// this is just to check the results. All your sentences are now stored in the ArrayList results
for (String string : results) {
System.out.println("" + string);
}
}
and this was my result when I tested the method:
this is my car
this is my
this is
this
is my car
is my
is
my car
my
car
Use Guava:
String yourOriginalString = "This is my car";
final Set<String> originalWords =
Sets.newLinkedHashSet(
Splitter.on(CharMatcher.WHITESPACE).trimResults().split(yourOriginalString));
final Set<Set<String>> variations = Sets.powerSet(originalWords);
for (Set<String> variation : variations) {
System.out.println(Joiner.on(' ').join(variation));
}
Output:
This
is
This is
my
This my
is my
This is my
car
This car
is car
This is car
my car
This my car
is my car
This is my car
Here is a possible way:
//Just a method that seperates your String into an array of words based on the spaces
//I'll leave that for you to figure out how to make
String[] array = getSeperatedWords(<yourword>);
List<StringBuffer> bufferArray = new ArrayList<StringBuffer>();
for(int i = 0; i < array.length; i++){
StringBuffer nowWord = array[i];
for(int j = i; j < array.length; j++{
nowWord.append(array[j]);
}
bufferArray.add(nowWord);
}
for(int i = 0; i < bufferArray.length; i++){
System.out.print(bufferArray.get(i));
}
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String var = "This is my car";
permute(var);
}
public static void permute(String var) {
if(var.isEmpty())
return;
String[] arr = var.split(" ");
while(arr.length > 0) {
for(String str : arr) {
System.out.print(str + " ");
}
arr = (String[]) Arrays.copyOfRange(arr, 0, arr.length - 1);
System.out.println();
}
String[] original = var.split(" ");
permute(implodeArray((String[]) Arrays.copyOfRange(original, 1, original.length), " "));
}
public static String implodeArray(String[] inputArray, String glueString) {
String output = "";
if (inputArray.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append(inputArray[0]);
for (int i=1; i<inputArray.length; i++) {
sb.append(glueString);
sb.append(inputArray[i]);
}
output = sb.toString();
}
return output;
}
}
Read this book, you will be a master on recursion: http://mitpress.mit.edu/sicp/

I want to split string without using split function?

I want to split string without using split . can anybody solve my problem I am tried but
I cannot find the exact logic.
Since this seems to be a task designed as coding practice, I'll only guide. No code for you, sir, though the logic and the code aren't that far separated.
You will need to loop through each character of the string, and determine whether or not the character is the delimiter (comma or semicolon, for instance). If not, add it to the last element of the array you plan to return. If it is the delimiter, create a new empty string as the array's last element to start feeding your characters into.
I'm going to assume that this is homework, so I will only give snippets as hints:
Finding indices of all occurrences of a given substring
Here's an example of using indexOf with the fromIndex parameter to find all occurrences of a substring within a larger string:
String text = "012ab567ab0123ab";
// finding all occurrences forward: Method #1
for (int i = text.indexOf("ab"); i != -1; i = text.indexOf("ab", i+1)) {
System.out.println(i);
} // prints "3", "8", "14"
// finding all occurrences forward: Method #2
for (int i = -1; (i = text.indexOf("ab", i+1)) != -1; ) {
System.out.println(i);
} // prints "3", "8", "14"
String API links
int indexOf(String, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If no such occurrence exists, -1 is returned.
Related questions
Searching for one string in another string
Extracting substrings at given indices out of a string
This snippet extracts substring at given indices out of a string and puts them into a List<String>:
String text = "0123456789abcdefghij";
List<String> parts = new ArrayList<String>();
parts.add(text.substring(0, 5));
parts.add(text.substring(3, 7));
parts.add(text.substring(9, 13));
parts.add(text.substring(18, 20));
System.out.println(parts); // prints "[01234, 3456, 9abc, ij]"
String[] partsArray = parts.toArray(new String[0]);
Some key ideas:
Effective Java 2nd Edition, Item 25: Prefer lists to arrays
Works especially nicely if you don't know how many parts there'll be in advance
String API links
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Related questions
Fill array with List data
You do now that most of the java standard libraries are open source
In this case you can start here
Use String tokenizer to split strings in Java without split:
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
This is the right answer
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
/**
* My method split without javas split.
* Return array with words after mySplit from two texts;
* Uses trim.
*/
public class NoJavaSplit {
public static void main(String[] args) {
String text1 = "Some text for example ";
String text2 = " Second sentences ";
System.out.println(Arrays.toString(mySplit(text1, text2)));
}
private static String [] mySplit(String text1, String text2) {
text1 = text1.trim() + " " + text2.trim() + " ";
char n = ' ';
int massValue = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.charAt(i) == n) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text1.length(); j++) {
if (text1.charAt(j) == n) {
splitArray[i] = text1.substring(0, j);
text1 = text1.substring(j + 1, text1.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
}
you can try, the way i did `{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for(int i = 0; i <str.length();i++) {
if(str.charAt(i)==' ') { // whenever it found space it'll create separate words from string
System.out.println();
continue;
}
System.out.print(str.charAt(i));
}
sc.close();
}`
The logic is: go through the whole string starting from first character and whenever you find a space copy the last part to a new string.. not that hard?
The way to go is to define the function you need first. In this case, it would probably be:
String[] split(String s, String separator)
The return type doesn't have to be an array. It can also be a list:
List<String> split(String s, String separator)
The code would then be roughly as follows:
start at the beginning
find the next occurence of the delimiter
the substring between the end of the previous delimiter and the start of the current delimiter is added to the result
continue with step 2 until you have reached the end of the string
There are many fine points that you need to consider:
What happens if the string starts or ends with the delimiter?
What if multiple delimiters appear next to each other?
What should be the result of splitting the empty string? (1 empty field or 0 fields)
You can do it using Java standard libraries.
Say the delimiter is : and
String s = "Harry:Potter"
int a = s.find(delimiter);
and then add
s.substring(start, a)
to a new String array.
Keep doing this till your start < string length
Should be enough I guess.
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class WithoutSpit_method {
public static void main(String arg[])
{
char[]str;
String s="Computer_software_developer_gautam";
String s1[];
for(int i=0;i<s.length()-1;)
{
int lengh=s.indexOf("_",i);
if(lengh==-1)
{
lengh=s.length();
}
System.out.print(" "+s.substring(i,lengh));
i=lengh+1;
}
}
}
Result: Computer software developer gautam
Here is my way of doing with Scanner;
import java.util.Scanner;
public class spilt {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the String to be Spilted : ");
String st = input.nextLine();
Scanner str = new Scanner(st);
while (str.hasNext())
{
System.out.println(str.next());
}
}
}
Hope it Helps!!!!!
public class StringWitoutPre {
public static void main(String[] args) {
String str = "md taufique reja";
int len = str.length();
char ch[] = str.toCharArray();
String tmp = " ";
boolean flag = false;
for (int i = 0; i < str.length(); i++) {
if (ch[i] != ' ') {
tmp = tmp + ch[i];
flag = false;
} else {
flag = true;
}
if (flag || i == len - 1) {
System.out.println(tmp);
tmp = " ";
}
}
}
}
In Java8 we can use Pattern and get the things done in more easy way. Here is the code.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
static void splitString(String s, int index) {
char[] firstPart = new char[index];
char[] secondPart = new char[s.length() - index];
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (i < index) {
firstPart[i] = s.charAt(i);
} else {
secondPart[j] = s.charAt(i);
if (j < s.length()-index) {
j++;
}
}
}
System.out.println(firstPart);
System.out.println(secondPart);
}
import java.util.Scanner;
public class Split {
static Scanner in = new Scanner(System.in);
static void printArray(String[] array){
for (int i = 0; i < array.length; i++) {
if(i!=array.length-1)
System.out.print(array[i]+",");
else
System.out.println(array[i]);
}
}
static String delimeterTrim(String str){
char ch = str.charAt(str.length()-1);
if(ch=='.'||ch=='!'||ch==';'){
str = str.substring(0,str.length()-1);
}
return str;
}
private static String [] mySplit(String text, char reg, boolean delimiterTrim) {
if(delimiterTrim){
text = delimeterTrim(text);
}
text = text.trim() + " ";
int massValue = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == reg) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text.length(); j++) {
if (text.charAt(j) == reg) {
splitArray[i] = text.substring(0, j);
text = text.substring(j + 1, text.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
public static void main(String[] args) {
System.out.println("Enter the sentence :");
String text = in.nextLine();
//System.out.println("Enter the regex character :");
//char regex = in.next().charAt(0);
System.out.println("Do you want to trim the delimeter ?");
String delch = in.next();
boolean ch = false;
if(delch.equalsIgnoreCase("yes")){
ch = true;
}
System.out.println("Output String array is : ");
printArray(mySplit(text,' ',ch));
}
}
Split a string without using split()
static String[] splitAString(String abc, char splitWith){
char[] ch=abc.toCharArray();
String temp="";
int j=0,length=0,size=0;
for(int i=0;i<abc.length();i++){
if(splitWith==abc.charAt(i)){
size++;
}
}
String[] arr=new String[size+1];
for(int i=0;i<ch.length;i++){
if(length>j){
j++;
temp="";
}
if(splitWith==ch[i]){
length++;
}else{
temp +=Character.toString(ch[i]);
}
arr[j]=temp;
}
return arr;
}
public static void main(String[] args) {
String[] arr=splitAString("abc-efg-ijk", '-');
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
You cant split with out using split(). Your only other option is to get the strings char indexes and and get sub strings.

Categories

Resources