Home / Archive by tag 'string'

Posts tagged "string"

Interpolating functions and expressions in perl strings

We can construct more complex templates with scalar variable and function interpolation. Developers generally want a function call or expression to expand within a string.

You can break up your expression into distinct concatenated pieces:

$endresult = $varone . funccall() . $vartwo;   # scalar only

Or you can use @{[ LIST EXPR ]} or ${ \ (SCALAR EXPR ) } expansions:

$endresult = "SOMETHING @{[ LIST EXPR ]} MORE SOMETHING";
$endresult = "SOMETHING ${\( SCALAR EXPR )} MORE SOMETHING";

Split string into characters in perl

We can process a string one character at a time by splitting it using the split function and a null parameter defined as //

$string = "w3m";
@strarr = split(//, $string);

Output:
strarr[0] = w
strarr[1] = 3
strarr[2] = m

We can also use a loop to extract characters as

while ($string =~ /(.)/g) { # . is never a newline here
    print $1
}

Exchange variables without temporary variable in perl

The most common approach to exchanging variables is to use a third temporary variable to swap content.

$temp    = $a;
$a       = $b;
$b       = $temp;

Perl’s list offers an easy way to swap elements

$a = "item";
$b = "raja";
($a, $b) = ($b, $a);        # the first shall be last -- and versa vice

Extract string column with unpack in perl

$a = "perl tutorials";
$b = unpack("x6 A8", $a); # skip 6, read next 8
print $b;

Output:
utorials


Convert Base64 encoded bitmap to file in C#

The static FromBase64String method on the Convert class returns a byte[] that contains the decoded elements of the String.

byte[] imageBytes = bmpAsString.Base64DecodeString();
using (FileStream fstrm = new FileStream(@"C:\recdcopy.bmp",FileMode.CreateNew, FileAccess.Write))
{
    using (BinaryWriter writer = new BinaryWriter(fstrm))
    {
        writer.Write(imageBytes);
    }
}

Encode binary data As Base64 in C#

Generally a byte[] representing some binary information, such as a bitmap is encoded into a string so that it can be sent over a binary-unfriendly transport, such as email, using Base64.

The static method Convert.ToBase64String on the Convert class can be used on a byte[] to encode to its String equivalent

Example:

using System;
using System.IO;
static class MyModClass
{
public static string Base64EncodeBytes(this byte[] inBytes)
{
return (Convert.ToBase64String(inBytes));
}
}

Replace a delimiting character within a string in C#

string CDString = "a,b,c,d,e";
CDString = CDString.Replace(',', ':');
Console.WriteLine(CDString);

This code creates a new string and then makes the CDString variable refer to it. The string in CDString now looks like this:
a:b:c:d:e


Remove method of the StringBuilder object

The Remove method of the StringBuilder class is not overloaded and is straightforward to use.

StringBuilder str1 = new StringBuilder("1234abc5678", 12);
str.Remove(4, 3);
Console.WriteLine(str);

Output:
12345678


Remove a substring from a string using C#

string name = "Raja, Item";
name = name.Remove(4, 1);
Console.WriteLine(name);

This code creates a new string and then sets the name variable to refer to it. The string contained in name now looks like this:
Raja Item


Test empty strings in perl

To test for a empty string simply do the following:

if ($mystring eq "") {
#string is empty
}

For a null or undefined value do:

if($mystring) {
#variable is undefined
}
if($mystring eq undef) {
#variable is undefined
}

Swap the first and last letters in a string using perl

$str = "take a ham";
(substr($str,0,1), substr($str,-1)) = (substr($str,-1), substr($str,0,1));
print $str;

Output:
make a hat


Using unpack function in perl

The unpack function gives only read access, but is faster when you have many substrings to extract.

# get a 5-byte string, skip 3, then grab 2 8-byte strings, then the rest
($leading, $s1, $s2, $trailing) = unpack("A5 ×3 A8 A8 A*", $data);
 
# split at five byte boundaries
@fivers = unpack("A5" × (length($string)/5), $string);
 
# chop string into individual characters
@chars  =unpack("A1" × length($string), $string);

Replace substring with string using perl

$string = "This is what you have";
print $string;
substr($string, 5, 2) = "wasn't"; # change "is" to "wasn't"

Get substring from string using perl

$string = "This is what you have";
#         +012345678901234567890  Indexing forwards  (left to right)
#          109876543210987654321- Indexing backwards (right to left)
 
$first  = substr($string, 0, 1);  # "T"
$start  = substr($string, 5, 2);  # "is"
$rest   = substr($string, 13);    # "you have"
$last   = substr($string, -1);    # "e"
$end    = substr($string, -4);    # "have"
$piece  = substr($string, -8, 3); # "you"

Access or modify substring using Perl

If developers want to access or modify just a portion of a string, the substring function in perl can be used. An example usage would be to read a fixed-width record and to extract the individual fields.

The substr function lets you read from and write to bits of the string.

$value = substr($string, $offset, $count);
$value = substr($string, $offset);
substr($string, $offset, $count) = $newstring;
substr($string, $offset)         = $newtail;

Here docs in perl

”Here documents” are a way to quote a large chunk of text. The text can be interpreted as single-quoted, double-quoted, or even as commands to be executed, depending on how you quote the terminating identifier. Here we double-quote two lines with a here document:

$str = <"EOF";
This is a multiline here document
terminated by EOF on a line by itself
EOF

There’s no semicolon after the terminating EOF.


Quote operators in perl

We can specify strings in a perl program either with single quotes, double quotes using the quote-like operators q// and qq//, or “here documents.”

$string = q/Jon 'Main' Deva/;   # literal single quotes

You can use the same character as delimiter, as we do with / here, or you can balance the delimiters if you use parentheses or parentheses-like characters:

$string = q[Jon 'Main' Deva];   # literal single quotes
$string = q{Jon 'Main' Deva};   # literal single quotes
$string = q(Jon 'Main' Deva);   # literal single quotes
$string = q<Jon 'Main' Deva>;   # literal single quotes

Defining strings and newlines in perl

The declaration below indicates two different characters, \ and an n.

$string = '\n';

Declaring literal with single quotes

$string = 'Jon \'Main\' Deva';

Double quotes interpolate variables and expand a lot of backslashed shortcuts: \n becomes a newline, \033 becomes the character with octal value 33, \cJ becomes a Ctrl-J, and so on.

$string = "\n";                     # a "newline" character
$string = "Jon \"Main\" Deva";  # literal double quotes

XML-RPC String Data Type

The string data type is the basic text string and is a primitive data type. It is similar to the string data type in PHP.

Example Declaration:

<param>
<value><string>Hello,Visitor!</string></value>
</param>

The string data type most common data type in XML-RPC and any values of the value element without data type tags inside will default to string.

Example of default string declaration:

<param>
<value>Goodbye,visitor!</value>
</param>

Read a file into a string using PHP

An entire file can be read into a single string using the file_get_contents() php function. The file function reads all the lines of a file and returns them in a single string.

Example code on how to file_get_contents():

<?php 
$file = file_get_contents("/tmp/file.txt");
print("Size of the file: ".strlen($file)."\n");
?>

Output:
Size of the file: 7362

The $file string contains all the contents of the file and can be used for manipulation.