# Java Strings



## Wozzer (Mar 20, 2012)

Hello,

I have a quick question. I have the following code...

String test = "Hello World!";

But I want to print out every character from the 'W' onwards. How would i go about doing this?

Cheers


----------



## Kreij (Mar 20, 2012)

There are a couple of ways you could do this.
You could use the substring method to read from index 6 through 11, or you could use the split method to write the two strings to a string array using the space as a delimiter, and then print out the second string in the array.


----------



## FordGT90Concept (Mar 20, 2012)

Or use a for loop:

```
for (i = test.indexOf('W'); i < test.length(); i++)
{
  System.out.print(test[i]);
}
```


----------



## Wozzer (Mar 20, 2012)

thanks guys


----------



## Kreij (Mar 20, 2012)

.. or if you really like typing a lot  ...

```
boolean foundW = false;

for (int i = 0; i < test.length(); i++)
{
    if (test[i] == 'W')
    {
        foundW = true;
    }

    if (foundW == true)
    {
        System.out.print(test[i]);
    }
}
```

lol ... I would just use

```
System.out.print(test.substring(6));
```


----------



## Aquinus (Mar 20, 2012)

```
String test = "Hello World!";
System.out.println(test.substring(test.indexOf('W')));
```

That is what I would do.

And depending if you want to preserve everything before or after if the string is going to change you might want to change indexOf to lastIndexOf.


----------



## Kreij (Mar 20, 2012)

HAH !! Mine's more efficient as it does not have to traverse the string to find the index of 'W'. 

Speaking of writing inefficient code just for the helluvit (C# code)...

```
MD5 md5Hash = MD5.Create();

String test = "Hello World!";
String desiredResults = "World!";

string desiredResultsHash = GetMD5(md5Hash, desiredResults);

for (int i = 0; i < test.length(); i++)
{
  string tempResultsHash = GetMD5(md5Hash, test.substring(i);
  if (tempResultsHash == desiredResultsHash)
  {
    Console.Writeln(test.substring(i));
    break;
  }
}


private string GetMD5(MD5 md5Hash, String input)
{
  byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
  StringBuilder sBuilder = new StringBuilder();

  for (int i = 0; i < data.Length; i++)
  {
    sBuilder.Append(data[i].ToString("x2"));
  }

    return sBuilder.ToString();
}
```

Feel free to over-engineer Wasley's question for a little good natured programming fun.


----------



## Aquinus (Mar 20, 2012)

Kreij said:


> HAH !! Mine's more efficient as it does not have to traverse the string to find the index of 'W'.
> 
> Speaking of writing inefficient code just for the helluvit (C# code)...
> 
> ...



Well, if we're aiming for efficiency we could just do this. 

```
System.out.print("World!\n");
```

Or we could not use java. 


```
#include <cstdio.h>
int main() {
    printf("World!\n");
}
```


----------



## Kreij (Mar 20, 2012)

You didn't follow the rules in the OP stating you have to use the "Hello World!" string.


----------



## Disparia (Mar 20, 2012)

```
class SuperStringSplit {
	private $str;

	public function __construct($str) {
		$this->str = $str;
	}

	public function SplitOn($chr) {
		if (($pos = strpos($this->str, $chr)) !== false) {
			return substr($this->str, $pos);
		}
		return $str;
	}
}

echo new SuperStringSplit('Hello World!')->SplitOn('W');
```


----------



## Kreij (Mar 20, 2012)

Love the class name Jizz 

I'm not a PHP guru, but can you do somthing like (assuming that you know the W exists in the string)? ...

```
$str = substr($test, strpos($test, 'W'));
```


----------



## FordGT90Concept (Mar 20, 2012)

That's pretty much what it does:

```
if (([u]$pos[/u] = [b]strpos[/b]($this->str, $chr)) !== false) { 
            return [b]substr[/b]($this->str, [u]$pos[/u]); 
        }
```
The "!== false" makes it evaluate false if $chr does not exist in $this->str.  It would then fall to "return $str".


----------



## Kreij (Mar 20, 2012)

Yeah, I know Ford. I was just trying to drum up a little action in the P&W section. Sigh, tough crowd.

For others ...
A boolean result will typically evaluate a zero to false, and a positive integer to true.
In the case of a string (which is actuallly a character array), if the character resides at an index of zero (the first position in an array), using != will return false even though the character was found.
The php operator "!==" will not return a false if it evaluates to zero (which is a valid array index).
Just be aware that using the "===" operator may not always evalute as you suppose it would (ie. similar to "==").


----------



## Disparia (Mar 20, 2012)

Kreij said:


> Love the class name Jizz
> 
> I'm not a PHP guru, but can you do somthing like (assuming that you know the W exists in the string)? ...
> 
> ...



Yup. Ford has it down.

Only thing else to note is that strpos is case-sensitive while stripos isn't. Also, being able to access a class method on creation is a new feature in PHP 5.4.0. Just in case someone saw my example and tried to use their own class in the same manner.


```
# < 5.4.0
$sss = new SuperStringSplit('Hello World');
echo $sss->SplitOn('W');

# >= 5.4.0
echo new SuperStringSplit('Hello World!')->SplitOn('W');
```


----------



## Aquinus (Mar 20, 2012)

You could mix it up with a little bit of regex.

```
<?php
$str = "Hello World!\n";
print preg_replace('/(^.*)(?=W)/', '',  $str);
```


----------



## Kreij (Mar 20, 2012)

Lol .... I thought of that Aquinus, but decided to go with converting everything to hash values for added inefficiency.


----------



## Aquinus (Mar 20, 2012)

This thread started reminding me of this: http://refactormycode.com/codes/2-ruby-simple-loop


----------



## Kreij (Mar 20, 2012)

lol .. my fave from that thread ..

if !nuts
then woman
else man


----------



## Disparia (Mar 20, 2012)

The recursive function version.


```
function IwillFindYou($chr, $str, $pos = 0) {
	return !isset($str{$pos}) ? : (
		($str{$pos} == $chr) ? substr($str, $pos) : IwillFindYou($chr, $str, ++$pos)
	);
}

echo IwillFindYou('W', 'Hello World!');
```

Only a smidgen unnecessary. Could add a couple closures in there, other things.


----------

