2012-01-21 8 views
0

문자열의 다음 단어에서 문자의 개수를 가져 오려고합니다. 내 입력 I am John 경우 예를 들어, 출력은 다음과 같이해야합니다 :
while 루프가 PHP에서 제대로 작동하지 않습니까?

1 // count of 'I' 
4 // count of 'I am' 
9 // count of 'I am John' 

나는이 과정에 대한 PHP에서이 같은 코드를 사용

$string = 'I am John'; 
$words = explode(' ',$string); 
$count_words = count($words); 

$i =0; 
while ($i<=$count_words){ 
    $word_length =0; 
    $k=0; 
    while($k<=$i){ 
     $word_length = strlen($words[$k-1]); 
     $word_length = $word_length + strlen($words[$k]); 
     $k++; 
    } 
    $word_length = $word_length + $i; // there is "$i" means "space" 
    echo $word_length.'<br/>'; 
    $i++; 

} 

그러나이 같은 출력을 반환 :

1 
4 
8 
7 

왜? 내 오류는 어디에 있습니까? 내 코드는 어떻게되어야할까요?
미리 감사드립니다.

$i =0; 
while ($i<=$count_words){ 
    //.... 
} 

$count_words3,하지만 당신은 때문에 <=4 번 반복 :

+2

제목 : 아니요, 지금까지 가장 널리 사용되는 언어 중 가장 기본적이고 널리 사용되는 언어 구조 중 하나에서 버그를 발견하지 못했습니다. : o) – deceze

+0

ok :) 당신은 어떤 제목을 제안합니까? :) – John

+2

여기는 공짜입니다 : http://codepad.viper-7.com/3R02TK하지만 진지하게, 자신의 코드를 디버깅하는 법을 배우십시오. 그렇지 않으면 프로그래밍에서 아무 것도하지 못할 것입니다. 디버깅이란 무엇이 잘못되었는지를 파악하기 위해 단계별로 코드를 단계적으로 진행하는 것을 의미합니다. 'var_dump()'를 많이 사용하십시오. – deceze

답변

1
<?php 
$string = 'I am John'; 
$words = explode(' ',$string); 
$count_words = count($words); 
$i =0; 
while ($i<$count_words){ 
    if($i==0) { 
    $wordsc[$i] = strlen($words[$i]); 
    } else { 
    $wordsc[$i] = strlen($words[$i])+1+$wordsc[$i-1]; 
    } 
    echo $wordsc[$i]."<br>"; 
    $i++; 
} 
?> 
1

귀하의 오류가 여기에있다. 대신 <을 사용하십시오.

+0

고마워. 하지만 이제는 1 4 8을 반환합니다. 왜 결국 '8'이 될까요? 그러나 '8'대신 '9'가 있어야합니다. – John

+1

@ 존 코드에 더 많은 문제가 있습니다 - 첫 번째 반복에서 $ words [$ k-1]은 $ words [-1]이됩니다. 코드를 테스트 한 결과 코드가 인쇄되지 않습니다. –

+0

그래서, 당신은 무엇을 제안합니까? 나는 $ words [$ k-1]의 istead를 사용해야합니까? – John

1
  1. 많은 단어로 반복되었습니다. count를 사용하면 배열의 요소 수를 반환합니다. 배열은 0에서 시작한다는 것을 기억하십시오.
  2. $ word_length + strlen ($ words [$ k - 1]); // 당신이 1을 뺀다. 나는 당신이 countest offest를 만족 시키려하고 있다고 생각하지만, 0에서 -1을 빼서 첫 단어를 놓친다.

코드 스 니펫 START

//Set up the words 

$string = 'I am John'; 

$words = explode(' ',$string); 

$count_words = count($words); 

//Loop through the words 
$i =0; 

while ($i<$count_words){ 

$word_length =0; 
$k=0; 

$debugString = ''; 

//Loop through all the previous words to the current 
while($k<= $i){ 

    //dont really need this since were adding the word length later 
    //$word_length = strlen($words[$k]); 

    //if you -1 from 0 you will get an undefined offest notice. You 
    //want to look at your current word 
    $word_length = $word_length + strlen($words[$k]); 

    //A bit of debugging you can delete this once you have seen the results 
    $debugString = $debugString ." ".$words[$k]; 

    $k++; 
} 

$word_length = $word_length + $i ; // there is "$i" means "space" 

//Added the debugString for debugging so remove it once you have seen the results 
echo $word_length." " .$debugString.' <br/>'; 
$i++; 

} 

코드 스 니펫의 END 나는 매우 직접적으로 원하는 데이터를 생성하는 완전히 다른 접근 방식을 제공하기 위해 기쁘게 생각합니다

0

방법. (Demo of what is to follow)

var_export(preg_match_all('/ |$/','I am John',$out,PREG_OFFSET_CAPTURE)?array_column($out[0],1):'failure'); 

출력 :

array (
    0 => 1, 
    1 => 4, 
    2 => 9, 
) 

각 워드 증분 문자열의 길이를 결정 효과적으로 각 후미 공간 offset 또는 최종 단어를 결정하는 것과 동일 - 전체 문자열 길이. 임의의 배열을 조작 전으로 출력 할 PREG_OFFSET_CAPTURE

preg_match_all() :

array (
    0 => 
    array (
    0 => 
    array (
     0 => ' ', // <-- the space after 'I' matched by ' ' 
     1 => 1, 
    ), 
    1 => 
    array (
     0 => ' ', // <-- the space after 'am' matched by ' ' 
     1 => 4, 
    ), 
    2 => 
    array (
     0 => '', // <-- the end of the string (after 'John') matched by '$' 
     1 => 9, 
    ), 
), 
) 

array_column() 만 오프셋 값을 추출 $out[0]에 사용된다 (

preg_match_all()

이위한 내장 "플래그"를 갖는다 불필요한 공백과 빈 문자열은 생략).

array_reduce(preg_split('/(?=)/',$string),function($carry,$item){echo $carry+=strlen($item)," "; return $carry;},0); 
output: 1 4 9 

이것이 공백되는 "제로 폭"문자열에 문자열을 분할 : 여기


또, 전혀 다른 방법이다. 이는 폭발 과정에서 공간이 손실되지 않는다는 것을 의미합니다. 이는 간단한 추가를 위해 문자열과 하위 문자열 길이를 유지합니다.

관련 문제