• Skip to main content
  • Skip to primary sidebar

CodeBlogMoney

Make Money using Coding and Blogging

String

String to Char Array Java

June 7, 2020 by Jimmy

String to Char Array Java

This blog helps to convert Java String to a character array.

1. Logical Approach without any inbuilt functions.

Follow these steps:

  1. Create a String variable and assign a value.
  2. Use the length of the String variable to create an array of characters.
  3. Use a loop to iterate the String using an index.
  4. Assign a value at the index to a character array.
  5. Once loops complete, Characters array will be ready to use.
  6. Use a loop to print the character array.

Code:

public class StringToCharArray {
	
	 public static void main( String args[] ) 
	    { 
		    //1. Create a String variable and assign a value
	        String cbm = "CodeBlogMoney"; 
	        
	        int lengthOfString = cbm.length();
	  
	        //2.Use the length of the String variable to create an array of characters 
	        char[] arrayOfCharacters = new char[ lengthOfString ]; 
	  
	        // 3. Use a loop to iterate the String using an index.
	        for ( int i = 0; i < lengthOfString; i++ ) { 
	        	
	        	// 4 Assign a value at the index to a character array.
	        	arrayOfCharacters[i] = cbm.charAt(i); 
	        
	        } // 5. Once loops complete, Characters array will be ready to use.
	  
	        // 6. Use a loop to print the character array
	        for ( char valueofChar : arrayOfCharacters ) { 
	            
	        	System.out.println( valueofChar ); 
	        
	        } 
	    } 
}

Output of above code:

C
o
d
e
B
l
o
g
M
o
n
e
y

2. Using toCharArray() function

java.lang.String has toCharArray() which converts String to array of characters and return the new object of array.

Follow these steps

  1. Define a string object with value.
  2. Use toCharArray() to return the array of characters
  3. Print the values of the character of array.

Code

public class StringToCharArrayUsingInbuildMethod {
	
	 public static void main( String args[] ) 
	    { 
		    //1. Define a string object with value
	        String cbm = "CodeBlogMoney"; 
 
	        //2.Use toCharArray() to return the array of characters
	        char[] arrayOfCharacters = cbm.toCharArray(); 
	          
	        // 3. Print the values of the character of array.
	        for ( char valueofChar : arrayOfCharacters ) { 
	            
	        	System.out.println( valueofChar ); 
	        
	        } 
	    } 
}

Output of above code:

C
o
d
e
B
l
o
g
M
o
n
e
y

More articles to check out.

JSON Example with Data Types Including JSON Array

Few online string tools to check out.

https://codebeautify.org/string-functions

Filed Under: Java Tagged With: Array, String

Reverse String in Python – Best Approach Given

December 9, 2016 by Jimmy

There are many ways to reverse string in Python. If you are familiar with c , c++ and java and don’t want to use any reverse function then someone could write the logic like:

1. Using the swapping last char with first and do that until the middle character. Remember we used to do this kind of exercise in C, 101?

2. Second would be like to take a new string and add 1 by 1 character from the opposite order of the String. This may take up too much space if you have Essay to reverse.

Note: String is immutable in Python similar to in Java. So it will not change the string if you try to modify, it will create the new String.

Firstly I have not seen a use case where I need to reverse a string unless you are trying to work on Cryptography.

This is enough talking.

Let’s do the reverse string with Python.

Reverse String in Python – Best Approach

This is the best and effective way to reverse a string.

string_sample = "Hello World"

reversed_string  = string_sample[::-1]

print(reversed_string)

This is the very astonished result by writing [::-1] it reverse the String and this is the fastest way to reverse a string.

This is called extended slice syntax. It works by writing [begin:end:step] – (minus sign) by leaving begin and end off and by writing a step of -1 , this will reverse a string.

Here are some other ways to reverse a string in python.

Reverse a String using the recursive function.

def reverse(string):
    if len(string) <= 1:
        return string

    return reverse(string[1:]) + string[0]

string_sample = "Hello World"

print(reverse(string_sample))

Reverse a String by using Extra String Variable

Reverse a string by using another string variable and adding character one by one in the opposite of the given string.

def reverse(string):
    new_string = ''
    index = len(string)
    while index:
        index -= 1
        new_string += string[index]
    return new_string

string_sample = "Hello World"
print(reverse(string_sample))

This approach may hurt the performance of the application based on the string length.

So the best approach is to use  [::-1] and fastest.

Filed Under: Python Tagged With: python, Reverse, String

Python String Concatenation and String Formatting

November 30, 2016 by Jimmy

Python String Concatenation is the process for joining small string to make the bigger. For example, you can create a full name by joining two string-like Firstname and Lastname. Formatting will help to display variable in or end of the string.

Python String Concatenation

Python provides the easy way to concatenate Strings by using + (plus)  and * (star) Sign. There are other methods such as append(), join() and format().

Using + 

+ will adds values on either side of the operator

Here is an example :

>>> str1 = "Jhon"
>>> str2 = "Doe"
>>> print str1 + " " + str2
Jhon Doe

Using *

*  Creates new strings, concatenating multiple copies of the same string.

Here is an example :

>>> "John" * 3
'JohnJohnJohn'

String Formatting in Python

You might have the experience to use C language to print String and Integer using %s and %d. Python has similar string formatting to create new, formatted strings. The % operator is used to format variables.

Here are the examples:

>>> name = "John Doe"
>>> print "Hello, %s How are you?" % name
Hello, John Doe How are you?
>>>

String formatting using two and more than values using the tuple. A tuple is a sequence of immutable Python objects. Tuples use parentheses.

>>> name = "John Doe"
>>> salary = 10000
>>> period = "Month"
>>> print "%s earns %d per month." % (name, salary)
John Doe earns 10000 per month.
>>> print "%s earns %d per %s." % (name, salary, period)
John Doe earns 10000 per Month.

Python is supporting other function like append and join to manipulate String data.

Related Python Articles:

Read JSON File using Python Code and Prompt

JSON Pretty Print using Python- with Examples

Check out this Python code Formatter

Filed Under: Python Tagged With: Concatenation, formatting, python, String, tuple

10 Python Tips and Tricks for Beginner and 9th is interesting

November 28, 2016 by Jimmy

Today Python is one of the most popular languages for coding in Unix/Linux world. You can find it everywhere from Web development to Server Component development, XML parsing to configuration management. Here I will be mentioning 10 Python tips and tricks for developers.

Python is pre-installed in many Operating Systems which released in last two year. Ubuntu, Redhat, Mac OS, Free BSD , Solaris, etc.

To check which version of python is installed go to shell and type:

$ python

This command will give you the version information of Python and start Python’s interactive interpreter.

Here are the few famous applications which are built using Python such as :

  • Youtube
  • OpenStak
  • Dropbox
  • Instagram

Here are 10 Python tips and tricks for Beginners and Experts.

1. Use Python Development Environment

By using Development Environment or IDE it will increase your productivity and easy to resolve error and warning. It will also help to debug the code, easy to navigate , integrate source control such as SVN, Git.

These are the recommended IDEs for Python Development.

  • PyDev – It’s free and Open Source Eclipse-based IDE . http://www.pydev.org/
  • IDLE: The Python built-in IDE, with auto-completion, helps to Format, Run, and Debug python code.
  • Other commercial versions are PyCharm(has Community version), WingIDE.

2. Calculate days between Today and Date.

import datetime

today = datetime.date.today()

someday = datetime.date(2017, 1, 1)

diff = someday - today

print (str(diff.days) +" days")

datetime module is used to find the days between two dates. this example will find the days between today and 1 Jan 2017.

3. Command line arguments while running Python Scripts

#file name is commandlinetest.py
import sys

print 'No of arguments passed:', len(sys.argv)
print 'List of arguments :', str(sys.argv)

run this script:

$ python commandlinetest.py 10 20 30

Output
No of arguments passed: 3
List of argumenrs : ['commandlinetest.py', '10', '20', '30']

sys module will have the information about arguments passed by accessing sys.argv variable. sys.argv is a list of strings representing the arguments on the command-line.

4. String Searching made easy

The first Method will check if a string contains another string by using the in syntax. in takes two arguments, first on the left and second on the right, and returns True if the left argument is contained within the right argument.

s = "This is a String finding program"

# Method 1
if 'String' in s:
    print('String is found in this program')

# Method 2
if s.find('String') != -1:
    print('String is at ' , s.index('String'))

Second Method offers a Library method called find(). This method is used with String Variable and it returns the position of the index of desired string. If the string is not found then -1 is returned.

5. Generating Random Numbers

Python is having the random library for generating random numbers. By default random library uses system time to generate random numbers.

import random

print('Random number:->' , random.randrange(10));

print('Random Range Between 10 to 20:->' , random.randrange(10,20));

print('Random with Floating values:->' , random.uniform(0,10));

Output :
Random number:-> 9
Random Range Between 10 to 20:-> 13
Random with Floating values:-> 5.012076169955613

random.randrange(10) sets the limit from 0 to 10 and return numbers between 0 to 10.

random.randrange(10,20) gives random values between 10 to 20.

random.uniform gives the result with floating value.

6. Opening WebBrowser from Python Script

import webbrowser

webbrowser.open('http://codebeautify.org')

webbrowser module provides the easy way to open system’s default browser with URL mention in open method.

7. Calculate Program Execution time

import time

start_time = time.time()

add = 0
for i in range(1, 10000):
    add =add + i
print(add)

print("\n--- %s seconds ---" % (time.time() - start_time))

Many applications require a very precise time measurement. For this purpose, Python provides methods in time module. These methods will help you to measure execution time taken by the block of code.

In Linux and Unix, this command can let us know the execution of the python program.

$ time python nameofprogram.py

8. Converting the List to a String for Print

#declaring List
mylist = ['one', 'two', 'three']

print (', '.join(mylist))
print ('\n'.join(mylist))

To combine any list of strings into a single string, use the join method of a string object. First print statement will join string with ” , ” and second will add new line.

Output:
one, two, three
one
two
three

9. Strings Concatenating using ” + ” and more.

Python uses + and * from manipulating String.

Using +

$ python
>>> print "Jhon" + "Doe"
JhonDoe

Using *

$python
>>> print "Jhon" * 3
JhonJhonJho

10. Sorting Array of String

mylist = ['one', 'two', 'three', 'four', 'five']

mylist.sort()

for x in mylist:
    print (x);

Output:
five
four
one
three
two

Let me know your views and best Python tips in a comment below.

Filed Under: Python Tagged With: python, String, Tips, Tricks

Primary Sidebar

Categories

  • Blogging
  • HTML
  • Java
  • JavaScript
  • jQuery
  • JSON
  • MySql
  • Performance
  • PHP
  • Problem Solving
  • Python
  • Testing
  • XML

Copyright © 2021 · Metro Pro on Genesis Framework · WordPress · Log in